From fe1938d2f02607e57f8cc8c2f5176d1d096e0e73 Mon Sep 17 00:00:00 2001 From: lux worker Date: Mon, 30 Nov 2026 15:34:38 +0000 Subject: [PATCH 01/15] feat: serve switchback experiments on 1.4.0; stamp events in live epoch ms Ports the switchback work of feat/switchbacks (30f4a3b..27829c1) and the timestamp fix (23692f3) onto released 1.4.0, keeping 1.4.0's behaviour for everything that is not a switchback: - lib/absmartly/switchback.rb (assigner, attribute paths, cluster keys, serving) as on feat/switchbacks. - Context: per-period switchback slots, epoch generations installed with the snapshot, the Collector's resolution order, and a separate publish request for an exposure the batch would credit to another cluster. The switchback read takes its clock reading outside the assignment lock and exposes through 1.4.0's exposure claim, stamped with that reading; queue_exposure keeps its 1.4.0 contract (reads never call it). - Payloads without switchbacks take 1.4.0's single-request publish and read no extra clock. - Every timestamp is the current epoch millisecond (a Time stays one instant, a callable clock is read per call); publishedAt is never before an event in its batch. Co-Authored-By: Claude Opus 5.5 --- README.md | 22 + lib/a_b_smartly.rb | 13 +- lib/absmartly/switchback.rb | 330 ++++ lib/context.rb | 680 +++++++- lib/json/experiment.rb | 30 +- spec/absmartly_spec.rb | 2 +- spec/context_holdouts_spec.rb | 4 +- spec/context_shared_variable_keys_spec.rb | 37 +- spec/context_spec.rb | 2 +- spec/context_switchback_cluster_spec.rb | 1499 +++++++++++++++++ spec/context_switchback_spec.rb | 1436 ++++++++++++++++ spec/experiment_switchback_fields_spec.rb | 92 + .../switchback/attribute-path-cases.json | 16 + .../resources/switchback/golden-vectors.json | 1392 +++++++++++++++ .../resources/switchback_context.json | 93 + spec/switchback_internals_spec.rb | 276 +++ spec/switchback_support.rb | 122 ++ spec/timestamps_spec.rb | 121 ++ 18 files changed, 6097 insertions(+), 70 deletions(-) create mode 100644 lib/absmartly/switchback.rb create mode 100644 spec/context_switchback_cluster_spec.rb create mode 100644 spec/context_switchback_spec.rb create mode 100644 spec/experiment_switchback_fields_spec.rb create mode 100644 spec/fixtures/resources/switchback/attribute-path-cases.json create mode 100644 spec/fixtures/resources/switchback/golden-vectors.json create mode 100644 spec/fixtures/resources/switchback_context.json create mode 100644 spec/switchback_internals_spec.rb create mode 100644 spec/switchback_support.rb create mode 100644 spec/timestamps_spec.rb diff --git a/README.md b/README.md index 37c23b44..3db87c10 100644 --- a/README.md +++ b/README.md @@ -332,6 +332,28 @@ Experiments can be covered by holdouts set up on the Web Console. A holdout keep - Peeking (`peek_treatment`, `peek_variable_value`) never queues exposures. - Set the unit before reading a covered experiment. An experiment read with `treatment` or `variable_value` before its unit type is set gets no holdout arm; `set_unit` alone does not change that exposed assignment or expose the holdout for it. A later refresh that changes the experiment or its coverage can rebuild the assignment. The exception is an overridden experiment, as in the Java SDK: its holdout is exposed by the next `variable_value` read after `set_unit` (not by `treatment`); the override still wins. +### Switchback Experiments + +A switchback experiment is randomized over clusters and time: a variant is drawn for each cluster (for example, a store's region) and each period of a fixed time grid, and every unit in that cluster shares the period's draw; overrides, assignment rules, strict audiences, full-on, traffic and custom assignments can still change the variant a unit gets. Consecutive periods can draw the same variant. The SDK serves switchbacks set up on the Web Console with no code changes, as the Collector and the Java SDK do. Set the attribute that holds each unit's cluster value: + +```ruby +context.set_unit(:store_id, "store-123") +context.set_attribute(:region, "lisbon") # cluster attribute path "region" +# or a nested value, with the cluster attribute path "region/city": +# context.set_attribute(:region, { "city" => "lisbon" }) + +context.treatment("delivery_fee_test") # the variant of cluster "lisbon" in the current period +``` + +- The experiment names, in order, the unit types it is linked to and the attribute path holding each one's cluster value. The first linked unit, in that order, whose attribute has a value serves the experiment; its exposure is sent under that unit. +- A cluster value is a non-empty string, used as is, or an Integer, keyed by its decimal text. A Float (even `3.0`), `true`/`false`, a Hash, an Array, `""` and `nil` give no value. +- With no value, linked units that disagree, or a value the experiment does not allow, the unit gets control (variant 0) and no exposure is sent. Without a unit of a linked type, the experiment does not apply. +- Before the experiment's start the unit gets control and no exposure is sent; an assignment rule, a strict audience mismatch and full-on still apply. +- A period keeps a copy of the cluster attribute values it read, so changing a value you passed to `set_attribute` in place (a String's text, a Hash or Array entry) does not change the cluster served. Changing a key of an identity-compared Hash (`compare_by_identity`) in place is not supported. Set a new value with `set_attribute` instead. +- Set the cluster attribute before the first read in a period. Changing it mid-period, before the exposure, is not supported: the period keeps the value it first read, and the change takes effect in the next period. +- One exposure is sent per experiment and period while its assignment is unchanged. A change within the period that rebuilds it (a new custom assignment or override, a refresh that changes the experiment) sends one more. So does a period the clock returns to after it stopped being one of the two most recent. The attribute is read once per period: setting it again takes effect in the next period. An exposure whose cluster or serving unit the later attributes or units would change is published in a request of its own, with what its period read, so the Collector credits the cluster that was served. +- `set_override`, assignment rules, strict audiences, full-on and `set_custom_assignment` apply as for other experiments. Holdouts never apply to a switchback. + ### Custom Assignments Sometimes it may be necessary to override the automatic selection of a variant. For example, if you wish to have your variant chosen based on data from an API call. This can be accomplished using the `set_custom_assignment` method. diff --git a/lib/a_b_smartly.rb b/lib/a_b_smartly.rb index d607049c..637ca165 100644 --- a/lib/a_b_smartly.rb +++ b/lib/a_b_smartly.rb @@ -114,7 +114,7 @@ def initialize_from_params(endpoint, api_key, application, environment, timeout, def create_context(config) validate_params(config) - Context.create(get_utc_format, config, @context_data_provider.context_data, + Context.create(system_clock, config, @context_data_provider.context_data, @context_data_provider, @context_event_handler, @context_event_logger, @variable_parser, AudienceMatcher.new(@audience_deserializer), application: client_application, environment: client_environment) @@ -122,7 +122,7 @@ def create_context(config) def create_context_async(config) validate_params(config) - context = Context.create_async(get_utc_format, config, @context_data_provider, + context = Context.create_async(system_clock, config, @context_data_provider, @context_event_handler, @context_event_logger, @variable_parser, AudienceMatcher.new(@audience_deserializer), application: client_application, environment: client_environment) @@ -138,7 +138,7 @@ def create_context_async(config) def create_context_with(config, data) validate_params(config) - Context.create(get_utc_format, config, data, + Context.create(system_clock, config, data, @context_data_provider, @context_event_handler, @context_event_logger, @variable_parser, AudienceMatcher.new(@audience_deserializer), application: client_application, environment: client_environment) @@ -149,10 +149,13 @@ def context_data end private - def get_utc_format - Time.now.utc.iso8601(3) + def system_clock + SYSTEM_CLOCK end + SYSTEM_CLOCK = -> { Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond) } + private_constant :SYSTEM_CLOCK + # The application and environment names configured on the client seed the # audience evaluation map (the collector adds them server-side for publish). # Custom data providers may leave @client nil, so guard the reads. diff --git a/lib/absmartly/switchback.rb b/lib/absmartly/switchback.rb new file mode 100644 index 00000000..8e3e6549 --- /dev/null +++ b/lib/absmartly/switchback.rb @@ -0,0 +1,330 @@ +# frozen_string_literal: true + +require "json" +require "murmurhash3" + +module Absmartly + # Switchback serving, ported from java-sdk (SWITCHBACK.md and + # internal/Switchback*.java), which ports the Collector. Internal: nothing + # here is public API. + module Switchback + # Balanced-block switchback assignment. Port of the platform's + # SwitchbackAssignment (murmur3_32, seed 0): + # key = utf8(cluster_unit + "\u001f" + cycle_index) + # base_hash = murmur3_32(le64(seed) ++ le32(murmur3_32(key))) + # step_hash = murmur3_32(le32(base_hash) ++ le32(i)), i = arm_count-1 .. 1 + # j = min(i, floor(u32(step_hash) / 0xffffffff * (i + 1))) + # variant = permutation[period_index mod arm_count], cycle = floor(period_index / arm_count) + # Integers are exact here, so floor division needs no care at the 64-bit + # bounds; the seed is the signed 64-bit (seedHi << 32) | (seedLo & 0xffffffff). + # Any change breaks parity with the platform golden vectors. + module Assigner + NORMALIZER = 1.0 / 0xffffffff + SEPARATOR = "\u001f" + + def self.assign(cluster_unit, period_index, seed, arm_count) + require_valid_arm_count(arm_count) + cycle_index = period_index.div(arm_count) + fisher_yates_permutation(arm_count, base_hash(cluster_unit, cycle_index, seed))[period_index % arm_count] + end + + def self.base_hash(cluster_unit, cycle_index, seed) + key = "#{cluster_unit}#{SEPARATOR}#{cycle_index}".encode(Encoding::UTF_8).b + key_hash = MurmurHash3::V32.str_hash(key) + MurmurHash3::V32.str_hash([seed & 0xffffffff, (seed >> 32) & 0xffffffff, key_hash].pack("V3")) + end + + def self.fisher_yates_permutation(arm_count, base_hash) + require_valid_arm_count(arm_count) + permutation = (0...arm_count).to_a + (arm_count - 1).downto(1) do |i| + step_hash = MurmurHash3::V32.str_hash([base_hash, i].pack("V2")) + # prob == 1.0 would map to i + 1 + j = [i, ((step_hash & 0xffffffff) * NORMALIZER * (i + 1)).floor].min + permutation[i], permutation[j] = permutation[j], permutation[i] + end + permutation + end + + def self.require_valid_arm_count(arm_count) + raise ArgumentError, "arm_count must be >= 2, got #{arm_count}" unless arm_count.is_a?(Integer) && arm_count >= 2 + end + end + + # The cluster key an attribute value yields, as the Collector's + # SwitchbackClusterKeys.normalize: a non-empty String as-is, an Integer as + # its base-10 text. nil, "", booleans, every Float (3.0 included), objects + # and arrays yield none. The key is passed to Assigner unhashed. + module ClusterKeys + def self.normalize(value) + case value + when String then value.empty? ? nil : value + when Integer then value.to_s + end + end + end + + # A cluster attribute path, resolved like the Collector's + # SwitchbackAttributePath: "/" separates segments, a segment wrapped in ' + # or " is a literal key, and an unquoted segment that Guava Ints.tryParse + # accepts (ASCII digits, optional leading '-', in int range) indexes an + # Array and nothing else. Every other segment reads a Hash key. A path is + # malformed when a quote is unterminated or it contains a '.' anywhere + # (dotted paths are not a nesting syntax). + class AttributePath + MAX_DEPTH = 64 + INT_MIN = -(2**31) + INT_MAX = (2**31) - 1 + + attr_reader :keys, :indices + + def initialize(keys, indices) + @keys = keys.freeze + @indices = indices.freeze + freeze + end + + # nil for an unsupported path: not a String, malformed, empty, or an + # index that is negative, first, last or directly after another index. + def self.parse_supported(path) + return nil unless path.is_a?(String) + + parsed = parse(path) + return nil if parsed.nil? || parsed.keys.empty? + + n = parsed.keys.length + parsed.indices.each_with_index do |index, i| + next if index.nil? + return nil if index.negative? || i.zero? || i == n - 1 || !parsed.indices[i - 1].nil? + end + parsed + end + + def self.parse(path) + return nil if path.include?(".") + + keys = [] + indices = [] + i = 0 + while i < path.length + if path[i] == "/" + i += 1 + next + end + + first = path[i] + if first == "'" || first == '"' + stop = path.index(first, i + 1) + return nil if stop.nil? + + keys << path[(i + 1)...stop] + indices << nil + i = stop + 1 + else + stop = path.index("/", i) || path.length + key = path[i...stop] + keys << key + indices << try_parse_int(key) + i = stop + end + end + new(keys, indices) + end + + # Guava Ints.tryParse: optional '-', then one or more ASCII digits, in + # int range; otherwise nil. "+1" and non-ASCII digits are not numbers. + def self.try_parse_int(text) + return nil unless text.match?(/\A-?[0-9]+\z/) + + value = Integer(text, 10) + value.between?(INT_MIN, INT_MAX) ? value : nil + end + + def root_key + keys[0] + end + + def resolve(attributes) + resolve_from(attributes, 0) + end + + # Resolves the path below root_key in an attribute value, read as the + # Collector reads it: the value's JSON encoding, as published, decoded + # back. nil when the value has no JSON encoding, or contains a cycle or + # nests deeper than MAX_DEPTH. + def resolve_attribute(root_value) + return nil if root_value.nil? + + decoded = case root_value + when Integer, true, false then root_value + when String + # As published: UTF-8 text, so a UTF-16 string keys like its UTF-8 twin. + return utf8_string(root_value) if keys.length == 1 + + root_value + else + return nil unless acyclic_within_depth?(root_value, {}.compare_by_identity, 0) + + begin + JSON.parse([root_value].to_json)[0] + rescue StandardError + return nil + end + end + resolve_from(decoded, 1) + end + + private + # The string's JSON encoding decoded back, or nil when it has none. + def utf8_string(value) + return value if value.encoding == Encoding::UTF_8 && value.valid_encoding? + + # Binary bytes are published as UTF-8 text when they are valid UTF-8 (Ruby 3.x's JSON). + if value.encoding == Encoding::BINARY + text = value.dup.force_encoding(Encoding::UTF_8) + return text.valid_encoding? ? text : nil + end + + JSON.parse([value].to_json)[0] + rescue StandardError + nil + end + + def acyclic_within_depth?(value, path, depth) + children = case value + when Hash then value.values + when Array then value + else return true + end + return false if depth >= MAX_DEPTH || path.key?(value) + + path[value] = true + return false unless children.all? { |child| acyclic_within_depth?(child, path, depth + 1) } + + path.delete(value) + true + end + + def resolve_from(root, first) + current = root + (first...keys.length).each do |i| + current = step(current, keys[i], indices[i]) + return nil if current.nil? + end + current + end + + def step(current, key, index) + if !index.nil? + current.is_a?(Array) && index >= 0 && index < current.length ? current[index] : nil + elsif current.is_a?(Hash) + current[key] + end + end + end + + # Which unit serves a switchback and under which cluster key. Port of the + # Collector's ContextAPI.switchbackServing (R33): + # - the switchbackClusters map, in declared order, lists the linked unit + # types and the attribute path holding each one's cluster value; + # - no context unit of a linked type: the experiment does not apply (ABSENT); + # - otherwise each linked unit, in source order, reads the attribute at its + # source's path. The first with a value serves, and the value is the + # cluster key; units without a value are skipped; + # - INELIGIBLE, under the first linked unit: no value, two units disagree, + # or the allow-list is set and lacks the key; + # - ELIGIBLE otherwise. + # A missing, empty or unreadable map takes the legacy path instead. + class Serving + ABSENT = 0 + INELIGIBLE = 1 + ELIGIBLE = 2 + + # unit_type is the serving unit when ELIGIBLE, the first linked unit when + # INELIGIBLE, nil when ABSENT. cluster_key is the raw key when ELIGIBLE. + attr_reader :status, :unit_type, :uid, :cluster_key + + def initialize(status, unit_type = nil, uid = nil, cluster_key = nil) + @status = status + @unit_type = unit_type + @uid = uid + @cluster_key = cluster_key + freeze + end + + # units maps a unit type (String) to its uid; the context holds at most + # one uid per type, so the declared source order alone decides which + # unit serves. read returns the raw value at a path, or nil. + def self.resolve(source_types, source_paths, allowed_values, units) + first = nil + serving = nil + key = nil + disagreement = false + source_types.each_with_index do |type, s| + uid = units[type] + next if uid.nil? + + first ||= [type, uid] + value = ClusterKeys.normalize(yield(source_paths[s])) + next if value.nil? + + if key.nil? + key = value + serving = [type, uid] + elsif key != value + disagreement = true + end + end + + return new(ABSENT) if first.nil? + return new(INELIGIBLE, *first) if key.nil? || disagreement || !allowed?(allowed_values, key) + + new(ELIGIBLE, serving[0], serving[1], key) + end + + # The Collector's path for a missing, empty or unreadable cluster map: + # a unit of the declared unitType only identifies an ineligible control; + # without one the experiment does not apply. + def self.legacy(unit_type, units) + uid = unit_type.nil? ? nil : units[unit_type.to_s] + uid.nil? ? new(ABSENT) : new(INELIGIBLE, unit_type.to_s, uid) + end + + # nil or [] admits every value, as in the Collector. Any other non-Array + # admits none. A scalar entry matches its JSON text, as Jackson coerces + # it into the Java SDK's String[] (17 as "17", true as "true", 1.5 as + # "1.5"); an object or array entry matches nothing. + def self.allowed?(allowed_values, key) + return true if allowed_values.nil? || (allowed_values.is_a?(Array) && allowed_values.empty?) + return false unless allowed_values.is_a?(Array) + + allowed_values.any? { |allowed| allowed_text(allowed) == key } + end + + def self.allowed_text(allowed) + case allowed + when String then allowed + when Integer, true, false then allowed.to_s + when Float then allowed.finite? ? allowed.to_s : nil + end + end + + # The linked unit types of a cluster map, in declared order; nil for a + # missing, empty or non-Hash map. + def self.source_types(clusters) + return nil unless clusters.is_a?(Hash) && !clusters.empty? + + clusters.keys.map(&:to_s) + end + + # The parsed paths, parallel to source_types; nil when the map is + # missing, empty, not a Hash, or any path is unsupported. + def self.source_paths(clusters) + return nil unless clusters.is_a?(Hash) && !clusters.empty? + + paths = clusters.values.map { |path| AttributePath.parse_supported(path) } + paths.include?(nil) ? nil : paths + end + end + end +end diff --git a/lib/context.rb b/lib/context.rb index 44a25085..eee96ec3 100644 --- a/lib/context.rb +++ b/lib/context.rb @@ -2,6 +2,7 @@ # Fiber.current and Fiber#alive? before Ruby 3.1. require "fiber" +require "set" require_relative "hashing" require_relative "type_utils" require_relative "variant_assigner" @@ -13,6 +14,7 @@ require_relative "json/exposure" require_relative "json/publish_event" require_relative "json/goal_achievement" +require_relative "absmartly/switchback" class Context # Immutable-by-convention snapshot swapped in with a single assignment so @@ -28,6 +30,20 @@ class EventsQueuedWhileClosing < StandardError; end # After this many overtaken walks a read returns the default, exposing nothing. VARIABLE_WALK_ATTEMPTS = 3 private_constant :VARIABLE_WALK_ATTEMPTS + SWITCHBACK = "switchback" + SWITCHBACK_KEY_SEPARATOR = "\u001f" + SWITCHBACK_RETAINED_PERIODS = 2 + # The Collector's anchor bounds: hour aligned, in [0, 10000-01-01T00:00:00Z). + SWITCHBACK_ANCHOR_ALIGNMENT_MS = 3_600_000 + SWITCHBACK_MAX_ANCHOR_MS = 253_402_300_800_000 + # One switchback's cache slots, all created under one generation. + SwitchbackEpoch = Struct.new(:generation, :periods) + # Returned by a lookup that found a switchback but was given no clock + # reading: the caller reads the clock, outside the assignment lock, and + # looks it up again with that reading. + NEEDS_CLOCK = Object.new.freeze + private_constant :SWITCHBACK, :SWITCHBACK_KEY_SEPARATOR, :SWITCHBACK_RETAINED_PERIODS, + :SWITCHBACK_ANCHOR_ALIGNMENT_MS, :SWITCHBACK_MAX_ANCHOR_MS, :SwitchbackEpoch, :NEEDS_CLOCK attr_reader :pending_count @@ -56,7 +72,9 @@ def initialize(clock, config, data_future, data_provider, variable_parser, audience_matcher, application, environment) if data_future.success? - @state = build_state(data_future.data_future) + state = build_state(data_future.data_future) + prepare_switchbacks(state) + @state = state log_event(ContextEventLogger::EVENT_TYPE::READY, data_future.data_future) else set_data_failed(data_future.exception) @@ -77,6 +95,7 @@ def set_data(data_future) if ready? failure = data_future.exception unless data_future.success? elsif state + prepare_switchbacks(state) @state = state else failure = data_future.exception @@ -237,7 +256,7 @@ def set_units(units) def set_attribute(name, value) check_not_closed? - @attributes.push(Attribute.new(name, value, @clock.to_i)) + @attributes.push(Attribute.new(name, value, now_millis)) @attrs_seq += 1 end @@ -250,11 +269,18 @@ def set_attributes(attributes) def treatment(experiment_name) check_ready?(true) + # A switchback is resolved, and exposed, at one clock reading. + now = @switchbacks_active ? now_millis : nil while true # rubocop:disable Style/InfiniteLoop -- no block allocation on the read path - assignment = assignment(experiment_name) + assignment = assignment(experiment_name, now, true) + if assignment.equal?(NEEDS_CLOCK) + # A refresh installed the first switchback while this call waited. + now = now_millis + next + end # set_unit may evict it between the lookup and the exposure claim: # then it is resolved again, so the variant served is the one exposed. - return assignment.variant unless claim_and_queue_exposure(assignment, experiment_name) == :evicted + return assignment.variant unless claim_and_queue_exposure(assignment, experiment_name, now) == :evicted end end @@ -262,6 +288,8 @@ def treatment(experiment_name) # or rule chose its variant. The holdouts covering it then expose once each, # in id order, from the arms pinned when the assignment was made, so a # refresh in between can't publish another holdout epoch (as in JS). + # A switchback the Collector records nothing for (no linked unit, an + # ineligible cluster, pre-anchor) exposes nothing. def queue_exposure(assignment) result = nil claim_and_queue_exposure(assignment) { |logged| result = logged } @@ -356,7 +384,7 @@ def track(goal_name, properties = nil) end achievement = GoalAchievement.new - achievement.achieved_at = @clock.to_i + achievement.achieved_at = now_millis achievement.name = goal_name achievement.properties = properties.nil? ? nil : properties.dup @@ -387,6 +415,7 @@ def refresh # refresh was in flight no longer leaves the context failed. Thread.handle_interrupt(Object => :never) do @ready_mutex.synchronize do + prepare_switchbacks(state) @state = state @failed = false @data_failed = nil @@ -440,8 +469,9 @@ def with_assignment_lock_if(locked, &block) # takes to evict), and a no-unit split assignment whose unit has since # been set counts as stale; then nothing is queued and :evicted is # returned so the caller resolves it again. Returns nil otherwise, never - # the logger's result (that is passed to the block). - def claim_and_queue_exposure(assignment, experiment_name = nil) + # the logger's result (that is passed to the block). now is the reading + # that chose a switchback's period; its exposure is stamped with it. + def claim_and_queue_exposure(assignment, experiment_name = nil, now = nil) return if assignment.exposed claimed = false @@ -467,7 +497,8 @@ def claim_and_queue_exposure(assignment, experiment_name = nil) # (a failed exposure left it cached): resolved again. A # direct queue_exposure call queues what it is given. elsif experiment_name.nil? || - (@assignment_cache[experiment_name.to_s].equal?(assignment) && !unit_now_set?(assignment)) + (@assignment_cache[assignment.switchback_key || experiment_name.to_s].equal?(assignment) && + !unit_now_set?(assignment)) @exposing[assignment] = Thread.current claimed = true :claimed @@ -489,7 +520,7 @@ def claim_and_queue_exposure(assignment, experiment_name = nil) # Only this assignment is claimed, without holding a lock over the # supplied clock; distinct nested or concurrent exposures can proceed. - exposed_at = @clock.to_i + exposed_at = assignment.switchback && !now.nil? ? now : now_millis exposure = nil holdout_exposures = nil @queue_mutex.synchronize do @@ -504,7 +535,13 @@ def claim_and_queue_exposure(assignment, experiment_name = nil) # override or rule chose its variant. The holdouts covering it then # expose once each, in id order, from the arms pinned when the # assignment was made (as in JS). - if !assignment.suppressed || assignment.overridden || assignment.rule_override + if assignment.switchback + # A switchback the Collector records nothing for exposes nothing. + unless assignment.switchback_silent + exposure = enqueue_exposure(assignment.name, assignment, exposed_at) + (@switchback_exposures ||= {}.compare_by_identity)[exposure] = assignment + end + elsif !assignment.suppressed || assignment.overridden || assignment.rule_override exposure = enqueue_exposure(assignment.name, assignment, exposed_at) end assignment.holdout_assignments&.each_with_index do |holdout_assignment, i| @@ -615,6 +652,7 @@ def flush(sealing: false, drop_rejected: false) result = @publish_mutex.synchronize do exposures = achievements = nil sent = nil + switchback_exposures = nil event_count = 0 # Failure installation and recovery both take this lock. Keep the # decision and snapshot together, but never hold it across publishing. @@ -629,6 +667,7 @@ def flush(sealing: false, drop_rejected: false) # grow by appending or are replaced whole, so a handler that # mutates its payload can't change what is removed. sent = [@exposures, exposures.size, @achievements, achievements.size] + switchback_exposures = @switchback_exposures&.dup end end failed_result @@ -642,25 +681,27 @@ def flush(sealing: false, drop_rejected: false) next nil end - event = PublishEvent.new - event.hashed = true - event.published_at = @clock.to_i - event.units = @units.map do |key, value| - Unit.new(key.to_s, unit_hash(key, value)) - end - event.exposures = exposures unless exposures.empty? - event.attributes = @attributes unless @attributes.empty? - event.goals = achievements unless achievements.empty? - # Like the JavaScript SDK, the publish event is logged once the batch is - # delivered; a failed delivery logs an error event instead. - begin - response = @event_handler.publish(self, event) - rescue StandardError => e - log_error(e) - raise + event = nil + if switchback_exposures.nil? + event = publish_event(now_millis, @units, @attributes, exposures, achievements) + # Like the JavaScript SDK, the publish event is logged once the batch is + # delivered; a failed delivery logs an error event instead. + begin + response = @event_handler.publish(self, event) + rescue StandardError => e + log_error(e) + raise + end + else + event, response = publish_with_switchbacks(exposures, achievements, switchback_exposures, sent) end - if publish_failed?(response) + if event.nil? + # Each request was logged as it was delivered. + remove_published(sent) + Thread.handle_interrupt(Object => :never) { claimed = take_close_pending } unless sealing + response + elsif publish_failed?(response) if response.is_a?(Exception) log_error(response) elsif response.respond_to?(:exception) && response.exception @@ -708,6 +749,7 @@ def drop_if_failed(sealing) @queue_mutex.synchronize do @exposures = [] @achievements = [] + @switchback_exposures = nil @pending_count = 0 end [true, sealing ? nil : @data_failed] @@ -721,7 +763,159 @@ def remove_published((exposures, exposure_count, achievements, achievement_count @exposures.shift(exposure_count) if @exposures.equal?(exposures) @achievements.shift(achievement_count) if @achievements.equal?(achievements) @pending_count = @exposures.size + @achievements.size + forget_switchback_exposures + end + end + + # Removes the events of the delivered requests of a partly delivered + # switchback publish; the rest stay queued for the next attempt. + def remove_delivered((exposures, _, achievements, _), events) + sent = {}.compare_by_identity + events.each do |event| + event.exposures&.each { |e| sent[e] = true } + event.goals&.each { |g| sent[g] = true } + end + @queue_mutex.synchronize do + @exposures.reject! { |e| sent.key?(e) } if @exposures.equal?(exposures) + @achievements.reject! { |g| sent.key?(g) } if @achievements.equal?(achievements) + @pending_count = @exposures.size + @achievements.size + forget_switchback_exposures + end + end + + # Drops the served state of switchback exposures no longer queued, so an + # ordinary publish returns to the single-request path. Caller holds + # @queue_mutex. + def forget_switchback_exposures + return if @switchback_exposures.nil? + + queued = {}.compare_by_identity + @exposures.each { |e| queued[e] = true } + @switchback_exposures.delete_if { |e, _| !queued.key?(e) } + @switchback_exposures = nil if @switchback_exposures.empty? + end + + # A publish body: hashed units, the attributes and the events. Its + # publishedAt is never before one of its events, which the Collector would + # reject with the whole batch, if the wall clock stepped back. + def publish_event(published_at, units, attributes, exposures, achievements) + event = PublishEvent.new + event.hashed = true + latest = published_at + i = 0 + while i < exposures.length + latest = exposures[i].exposed_at if exposures[i].exposed_at > latest + i += 1 + end + i = 0 + while i < achievements.length + latest = achievements[i].achieved_at if achievements[i].achieved_at > latest + i += 1 + end + event.published_at = latest + event.units = units.map do |key, value| + Unit.new(key.to_s, unit_hash(key.to_sym, value)) end + event.exposures = exposures unless exposures.empty? + event.attributes = attributes unless attributes.empty? + event.goals = achievements unless achievements.empty? + event + end + + # Publishes a batch holding switchback exposures. The Collector resolves a + # switchback's serving unit and cluster again from the batch's units and + # attributes at exposedAt; an exposure the batch would credit to another + # unit or cluster (a later set_unit, an attribute set in its millisecond, a + # clock rewind) is sent in a request of its own, with the units and + # attributes its period read. Requests go in order and stop at the first + # failure. Returns [event, response]: the single request's event, or nil + # once more than one request was delivered (each logged as delivered); + # on a failure, the failed request's event and response. + def publish_with_switchbacks(exposures, achievements, switchback_exposures, sent) + published_at = now_millis + response = nil + # The batch body is the snapshot the exposures are checked against, so a + # set_unit or set_attribute racing this publish can't change it. + units = @units.dup + attributes = @attributes.dup + separate = separate_switchback_exposures(exposures, switchback_exposures, units, attributes) + batch_exposures = separate.nil? ? exposures : exposures.reject { |exposure| separate.key?(exposure) } + events = [] + unless batch_exposures.empty? && achievements.empty? + events << publish_event(published_at, units, attributes, batch_exposures, achievements) + end + separate&.each { |exposure, (served_units, served)| events << publish_event(published_at, served_units, served, [exposure], []) } + + delivered = [] + events.each do |event| + begin + response = @event_handler.publish(self, event) + rescue StandardError => e + log_error(e) + remove_delivered(sent, delivered) unless delivered.empty? + raise + end + if publish_failed?(response) + remove_delivered(sent, delivered) unless delivered.empty? + return [event, response] + end + return [event, response] if events.length == 1 + + log_event(ContextEventLogger::EVENT_TYPE::PUBLISH, event) + delivered << event + end + [nil, response] + end + + # exposure => [units, attributes] for each switchback exposure that the + # batch body would credit to another unit or cluster, or nil. + def separate_switchback_exposures(exposures, switchback_exposures, units, attributes) + batch_units = units.transform_keys(&:to_s) + separate = nil + @assignment_mutex.synchronize do + exposures.each do |exposure| + assignment = switchback_exposures[exposure] + next if assignment.nil? || assignment.serving.status != Absmartly::Switchback::Serving::ELIGIBLE + next if served_at?(assignment, exposure.exposed_at, batch_units, attributes) + + payload = served_payload(assignment, exposure.exposed_at) + (separate ||= {}.compare_by_identity)[exposure] = payload unless payload.nil? + end + end + separate + end + + # The units and the attributes set by the slot's read. Should a clock + # rewind leave the attributes the read selected after exposedAt, those are + # sent stamped at exposedAt instead. + def served_payload(assignment, exposed_at) + units = assignment.serving_units + read = assignment.serving_attributes + return [units, read] if served_at?(assignment, exposed_at, units, read) + + selected = assignment.switchback_entry.switchback_source_paths.filter_map do |path| + latest_attribute(path.root_key, assignment.serving_read_at, read) + end.to_set + # Attributes that are not cluster sources are kept as they are. Of the + # cluster-source attributes only those the read selected stay, stamped no + # later than exposedAt, so a later value of the same name can't win. + roots = assignment.switchback_entry.switchback_source_paths.map(&:root_key) + clamped = read.filter_map do |a| + if selected.include?(a) + a.set_at > exposed_at ? Attribute.new(a.name, a.value, exposed_at) : a + elsif !roots.include?(a.name.to_s.strip) + a + end + end + served_at?(assignment, exposed_at, units, clamped) ? [units, clamped] : nil + end + + # Whether the Collector, resolving the cluster from these units and + # attributes at the exposure's instant, finds the one the slot served. + def served_at?(assignment, at, units, attributes) + view = resolve_switchback_serving(assignment.switchback_entry, at, units, attributes) + slot = assignment.serving + view.status == slot.status && view.unit_type == slot.unit_type && view.cluster_key == slot.cluster_key end def take_close_pending @@ -793,6 +987,21 @@ def enqueue_exposure(name, assignment, exposed_at) exposure end + # Epoch milliseconds, as the Collector reads every timestamp. A clock that + # responds to call is read on every call; a Time (or its ISO 8601 text) is + # a fixed instant, and an Integer is taken as milliseconds already. + def now_millis + clock = @clock + if clock.respond_to?(:call) + clock.call + elsif clock.is_a?(Time) + # Cached: the cached read path must not allocate. + @fixed_millis ||= (clock.to_r * 1000).floor + else + clock.to_i + end + end + def check_not_closed? if @closed raise IllegalStateException.new("ABSmartly Context is closed") @@ -884,6 +1093,12 @@ def invalidate_assignments_missing_unit(unit_type) @assignment_mutex.synchronize do exposing = @queue_mutex.synchronize { @exposing.dup } @assignment_cache.delete_if do |_name, assignment| + # A switchback resolved before any linked unit was set is resolved + # again; unless overridden it published nothing, so even an exposed one. + if assignment.switchback && assignment.serving.status == Absmartly::Switchback::Serving::ABSENT + next !assignment.overridden || !assignment.exposed + end + assignment.unit_type.to_s == unit_type && !assignment.exposed && missing_unit?(assignment) && !exposing.key?(assignment) end @@ -969,7 +1184,7 @@ def holdout_assignment(holdout, unit_type) (@holdout_assignments ||= {})[key] = assignment end - def audience_matches(entry, assignment) + def audience_matches(entry, assignment, unit_type = entry.data.unit_type) experiment = entry.data key = entry.rule_key cached_key = assignment.rule_key || NO_RULES @@ -991,7 +1206,7 @@ def audience_matches(entry, assignment) # the no-unit variant stays, so a unit arriving can't switch it. pinned_missing = assignment.rule_missing_unit && exposed_or_exposing?(assignment) rule_attrs = matcher_attributes(rule_matcher) - rule = resolve_rule(entry, rule_attrs, pinned_missing) + rule = resolve_rule(entry, rule_attrs, pinned_missing, unit_type) return false if rule&.first != assignment.rule_variant assignment.rule_missing_unit = rule ? rule.last : false @@ -1027,7 +1242,8 @@ def rule_matcher # Returns [variant, missing_unit], or nil to fall back to normal # assignment (as JS and Java do for an out-of-range variant or a split # without one percentage per variant). - def resolve_rule(entry, attrs, unit_pinned_missing) + # A switchback's split rule randomizes over its serving unit (unit_type). + def resolve_rule(entry, attrs, unit_pinned_missing, unit_type = entry.data.unit_type) experiment = entry.data return nil if entry.rules.nil? @@ -1040,7 +1256,6 @@ def resolve_rule(entry, attrs, unit_pinned_missing) end return nil if action.split.length != variant_count - unit_type = experiment.unit_type uid = unit_type.nil? || unit_pinned_missing ? nil : @units[unit_type.to_sym] return [experiment.full_on_variant || 0, true] if uid.nil? @@ -1052,16 +1267,35 @@ def resolve_rule(entry, attrs, unit_pinned_missing) # new as the previous one: a read that started before a refresh can't # overwrite assignments (or holdout arms) already built from newer data, # which would reset their exposed flag and expose them again. - def assignment(experiment_name) - @assignment_mutex.synchronize { cached_or_new_assignment(experiment_name, @state) } + # now is the caller's clock reading, so a switchback's period, its cluster + # attributes and its exposure's exposedAt all agree; without one, the + # clock is read once a switchback is found, unless needs_clock: then + # NEEDS_CLOCK is returned, so the caller exposes at the reading it takes. + def assignment(experiment_name, now = nil, needs_clock = false) + while true # rubocop:disable Style/InfiniteLoop -- no block allocation on the read path + assignment = @assignment_mutex.synchronize { cached_or_new_assignment(experiment_name, @state, now) } + return assignment if needs_clock || !assignment.equal?(NEEDS_CLOCK) + + now = now_millis + end end - def cached_or_new_assignment(experiment_name, state) - assignment = @assignment_cache[experiment_name.to_s] + # Returns NEEDS_CLOCK for a switchback when now is nil. + def cached_or_new_assignment(experiment_name, state, now = nil) exp_key = experiment_name.to_s.to_sym custom = @cassignments[exp_key] override = @overrides[exp_key] experiment = experiment(experiment_name.to_s, state) + if @switchbacks_active + if !experiment.nil? && experiment.switchback + return NEEDS_CLOCK if now.nil? + + return switchback_assignment(experiment_name.to_s, experiment, custom, override, now) + end + + drop_switchback_epoch(experiment_name.to_s) + end + assignment = @assignment_cache[experiment_name.to_s] # Built from the empty snapshot of a failed context that a refresh has # since recovered with the experiment: resolved again against the @@ -1217,13 +1451,23 @@ def cached_or_new_assignment(experiment_name, state) def resolve_variable_value(key, default_value, expose) key = key.to_s.to_sym winner = nil + now = nil attempts = 0 while true # rubocop:disable Style/InfiniteLoop -- no block allocation on the read path return default_value if attempts >= VARIABLE_WALK_ATTEMPTS attempts += 1 state = @state - winner = variable_assignment(key, expose, state) + # Read once per walk, so every switchback it resolves shares a reading. + now = @switchbacks_active ? now_millis : nil if now.nil? + winner = variable_assignment(key, expose, state, now) + if winner.equal?(NEEDS_CLOCK) + # A refresh installed the first switchback during the walk: it + # starts again at the reading taken now. + attempts -= 1 + now = now_millis + next + end visited = nil winner, visited = winner if winner.is_a?(Array) # A refresh, even one from a holdout's logger, restarts the walk. @@ -1240,7 +1484,7 @@ def resolve_variable_value(key, default_value, expose) break if winner.nil? || !expose || winner.exposed # The unit was set in between, so the walk may now pick another # candidate: it starts again, as java-sdk's settleExposure does. - break unless claim_and_queue_exposure(winner, winner.name) == :evicted + break unless claim_and_queue_exposure(winner, winner.name, now) == :evicted end return default_value if winner.nil? || winner.variables.nil? || !winner.variables.key?(key) @@ -1250,7 +1494,7 @@ def resolve_variable_value(key, default_value, expose) # Returns the winner, or, when exposing and a visited candidate still has # a holdout to expose, [winner, those candidates] (only then allocated); # the caller exposes them once the walk stands. - def variable_assignment(key, expose, state = @state) + def variable_assignment(key, expose, state = @state, now = nil) candidates = state.index_variables[key] return nil if candidates.nil? @@ -1261,7 +1505,8 @@ def variable_assignment(key, expose, state = @state) while i < candidates.length # Resolved from the state current under the assignment lock, so a read # that a refresh overtook can't reinstall an old assignment. - assignment = assignment(candidates[i].data.name) + assignment = assignment(candidates[i].data.name, now, true) + return NEEDS_CLOCK if assignment.equal?(NEEDS_CLOCK) # As in java-sdk, visited candidates' holdouts precede the winner's exposure. if expose && !assignment.holdout_assignments.nil? && (!assignment.exposed || assignment.overridden) && holdouts_pending?(assignment) @@ -1333,7 +1578,7 @@ def queue_holdout_exposures(assignment) # Checked again under the lock; this keeps warm reads off the clock and lock. return if holdout_assignments.all? { |holdout_assignment| holdout_assignment.nil? || holdout_assignment.exposed } - exposed_at = @clock.to_i + exposed_at = now_millis holdout_exposures = nil @queue_mutex.synchronize do check_not_closed? @@ -1475,7 +1720,17 @@ def build_state_maps(data) end experiment_variables.unconditional = experiment_variables.rule_key.equal?(NO_RULES) && (experiment.audience.nil? || experiment.audience.empty?) - holdout_ids = experiment.holdout_ids unless holdouts_by_id.empty? || !experiment.respond_to?(:holdout_ids) + # Holdouts never apply to a switchback. + if experiment.respond_to?(:randomization_type) && experiment.randomization_type == SWITCHBACK + clusters = experiment.switchback_clusters + experiment_variables.switchback = true + experiment_variables.switchback_grid = switchback_grid(experiment) + experiment_variables.switchback_source_types = Absmartly::Switchback::Serving.source_types(clusters) + experiment_variables.switchback_source_paths = Absmartly::Switchback::Serving.source_paths(clusters) + experiment_variables.switchback_source_roots = experiment_variables.switchback_source_paths&.to_set(&:root_key)&.freeze + end + holdout_ids = experiment.holdout_ids unless holdouts_by_id.empty? || experiment_variables.switchback || + !experiment.respond_to?(:holdout_ids) if holdout_ids.is_a?(Array) && !holdout_ids.empty? holdouts = holdout_ids.filter_map { |id| holdouts_by_id[holdout_id(id)] }.uniq.sort_by { |h| holdout_id(h.id) } experiment_variables.holdouts = holdouts unless holdouts.empty? @@ -1533,6 +1788,327 @@ def build_state_maps(data) State.new(data, index, index_variables, custom_fields) end + # Called right before state is installed, under the readiness lock (or + # from the constructor): a switchback keeps its generation while it is + # unchanged (see assign_switchback_generations). + def prepare_switchbacks(state) + assign_switchback_generations(state.index, @state.index) + # Set before the state, and kept once a switchback was installed: its + # epochs must still be dropped. + @switchbacks_active ||= state.index.each_value.any?(&:switchback) + end + + # A switchback keeps its generation while its previous definition was a + # switchback with the same identity; otherwise it gets a fresh one, so its + # cached slots are dropped on its next resolution (an epoch change). + def assign_switchback_generations(index, previous_index) + index.each do |name, installed| + next unless installed.switchback + + previous = previous_index[name] + installed.switchback_generation = if same_switchback_identity?(previous, installed) + previous.switchback_generation + else + @switchback_generation += 1 + end + end + end + + # id, iteration, the ordered cluster map, the allow-list, startAt, + # periodMs and design, plus unitType when either side takes the legacy + # path. Seed, split and the analysis-only fields are not identity. + def same_switchback_identity?(previous, installed) + return false if previous.nil? || !previous.switchback + + a = previous.data + b = installed.data + a.id == b.id && a.iteration == b.iteration && previous.switchback_grid == installed.switchback_grid && + ((!previous.switchback_source_paths.nil? && !installed.switchback_source_paths.nil?) || + a.unit_type == b.unit_type) + end + + def switchback_grid(experiment) + [Experiment.ordered_clusters(experiment.switchback_clusters), experiment.switchback_cluster_values, + experiment.switchback_start_at, experiment.switchback_period_ms, experiment.switchback_design_type] + end + + # Whether the Collector can serve the schedule: an hour-aligned start in + # [0, 10000-01-01), used as served, a period > 0 and at least two arms. + def switchback_schedule_servable?(experiment) + start_at = experiment.switchback_start_at + period_ms = experiment.switchback_period_ms + start_at.is_a?(Integer) && start_at >= 0 && start_at < SWITCHBACK_MAX_ANCHOR_MS && + (start_at % SWITCHBACK_ANCHOR_ALIGNMENT_MS).zero? && + period_ms.is_a?(Integer) && period_ms > 0 && + experiment.split.is_a?(Array) && experiment.split.length >= 2 + end + + # floor((now - startAt) / periodMs), or nil before the start, for an + # unservable schedule and on the legacy path. + def switchback_period(entry, now) + return nil if entry.switchback_source_paths.nil? || !switchback_schedule_servable?(entry.data) + + start_at = entry.data.switchback_start_at + now < start_at ? nil : (now - start_at).div(entry.data.switchback_period_ms) + end + + def switchback_seed(experiment) + ((experiment.seed_hi || 0) << 32) | ((experiment.seed_lo || 0) & 0xffffffff) + end + + # The Collector's switchbackServing at now. A missing, empty or unreadable + # cluster map takes the legacy path. + # units maps unit type names to uids and attributes is the attribute list + # read, so a publish can resolve the cluster again from its own payload. + def resolve_switchback_serving(entry, now, units = @units.transform_keys(&:to_s), attributes = @attributes) + if entry.switchback_source_paths.nil? + return Absmartly::Switchback::Serving.legacy(entry.data.unit_type, units) + end + + Absmartly::Switchback::Serving.resolve(entry.switchback_source_types, entry.switchback_source_paths, + entry.data.switchback_cluster_values, units) do |path| + attribute = latest_attribute(path.root_key, now, attributes) + attribute.nil? ? nil : path.resolve_attribute(attribute.value) + end + end + + # The attributes set so far, with the value of each cluster source copied, + # so a caller that later changes the object it set can't change the + # cluster the slot served or the body its exposure is published with. + def serving_snapshot(entry) + roots = entry.switchback_source_roots + return @attributes.dup if roots.nil? + + @attributes.map do |attribute| + next attribute unless roots.include?(attribute.name.to_s.strip) + + Attribute.new(attribute.name, copy_attribute_value(attribute.value), attribute.set_at) + end.freeze + end + + # A String, Array or Hash is copied with dup, so a subclass and a default + # proc are kept; a shared or cyclic part is copied once. Values are + # replaced in place, never through []=, so a subclass that rewrites keys + # is copied as is. Nesting deeper than a cluster path reads, and a value + # that dup does not copy or whose copy raises, are kept as they are. + def copy_attribute_value(value, copies = {}.compare_by_identity, depth = 0) + return value unless value.is_a?(String) || value.is_a?(Array) || value.is_a?(Hash) + return value if value.frozen? && value.is_a?(String) + return copies[value] if copies.key?(value) + return value if depth > Absmartly::Switchback::AttributePath::MAX_DEPTH + + copy = value.dup + return value if copy.equal?(value) || copy.frozen? + + copies[value] = copy + if copy.is_a?(Array) + copy.map! { |item| copy_attribute_value(item, copies, depth + 1) } + elsif copy.is_a?(Hash) + copy.transform_values! { |item| copy_attribute_value(item, copies, depth + 1) } + end + copy + rescue StandardError + copies[value] = value + end + + # The attribute the Collector records with an exposure at now: among those + # set at or before now with that (trimmed) name, the latest setAt, and on a + # tie the one set last. System attributes are never read. + def latest_attribute(name, now, attributes) + selected = nil + attributes.each do |attribute| + next unless attribute.set_at <= now && attribute.name.to_s.strip == name + selected = attribute if selected.nil? || attribute.set_at >= selected.set_at + end + selected + end + + # Port of java-sdk's switchback branch of getAssignment. Each period has + # its own slot; the bare-name slot serves before the anchor and for an + # unservable schedule. Caller holds @assignment_mutex. + def switchback_assignment(name, entry, custom, override, now) + epoch = @switchback_epochs[name] + drop_switchback_epoch(name) if !epoch.nil? && epoch.generation != entry.switchback_generation + + period = switchback_period(entry, now) + cache_key = period.nil? ? name : "#{name}#{SWITCHBACK_KEY_SEPARATOR}#{period}" + cached = @assignment_cache[cache_key] + cached = nil unless cached.nil? || cached.switchback + return cached if !cached.nil? && switchback_assignment_current?(cached, entry, custom, override) + + # The serving unit and cluster key are read once per slot. + serving = cached&.serving + read_at = cached&.serving_read_at + units = cached&.serving_units + attributes = cached&.serving_attributes + if serving.nil? || serving.status == Absmartly::Switchback::Serving::ABSENT + # The units and the attributes set so far, as the read sees them; an + # exposure that the final payload no longer resolves to this cluster is + # published with these. + units = @units.transform_keys(&:to_s).freeze + attributes = serving_snapshot(entry) + serving = resolve_switchback_serving(entry, now, units, attributes) + read_at = now + end + + assignment = Assignment.new + assignment.name = name + assignment.eligible = true + assignment.custom_assignment = custom + assignment.switchback = true + assignment.serving = serving + assignment.serving_read_at = read_at + assignment.serving_units = units + assignment.serving_attributes = attributes + assignment.switchback_entry = entry + assignment.id = entry.data.id + if override.nil? + resolve_switchback(assignment, entry, serving, custom, period) + else + assignment.unit_type = serving.unit_type || switchback_fallback_unit_type(entry) + assignment.overridden = true + assignment.variant = override + end + + variants = entry.data.variants + if !variants.nil? && assignment.variant >= 0 && assignment.variant < variants.length + assignment.variables = entry.variables[assignment.variant] || {} + end + + assignment.switchback_key = cache_key + @assignment_cache[cache_key] = assignment + retain_switchback_period(name, entry, period) + assignment + end + + # The Collector's order for an eligible cluster: rules (a split rule over + # the serving unit), audience, full-on, then, only with a current period, + # traffic on the serving unit's hash, custom assignment and the draw over + # the raw cluster key. Holdouts never apply. + def resolve_switchback(assignment, entry, serving, custom, period) + data = entry.data + assignment.iteration = data.iteration + assignment.traffic_split = data.traffic_split + assignment.full_on_variant = data.full_on_variant + assignment.rule_key = entry.rule_key + assignment.attrs_seq = @attrs_seq + assignment.variant = 0 + + if serving.status == Absmartly::Switchback::Serving::ABSENT + assignment.unit_type = switchback_fallback_unit_type(entry) + assignment.eligible = false + assignment.switchback_silent = true + return + end + + assignment.unit_type = serving.unit_type + assignment.assigned = true + if serving.status == Absmartly::Switchback::Serving::INELIGIBLE + assignment.eligible = false + assignment.switchback_silent = true + return + end + + rule_attrs = entry.rule_key.empty? ? nil : matcher_attributes(rule_matcher) + rule = rule_attrs.nil? ? nil : resolve_rule(entry, rule_attrs, false, serving.unit_type) + assignment.rule_variant = rule&.first + if rule + assignment.assigned = false + assignment.rule_override = true + assignment.rule_missing_unit = rule.last + assignment.variant = rule.first + return + end + + if !data.audience.nil? && data.audience.size > 0 + match = @audience_matcher.evaluate(data.audience, audience_attributes(rule_attrs)) + assignment.audience_mismatch = true if match && !match.result + end + if data.audience_strict && assignment.audience_mismatch + assignment.assigned = false + return + end + if data.full_on_variant != 0 + assignment.variant = data.full_on_variant + assignment.full_on = true + return + end + if period.nil? + assignment.eligible = false + assignment.switchback_silent = true + return + end + + assigner = variant_assigner(serving.unit_type, serving.uid) + if assigner.assign(data.traffic_split, data.traffic_seed_hi, data.traffic_seed_lo) != 1 + assignment.eligible = false + return + end + if !custom.nil? + assignment.variant = custom + assignment.custom = true + return + end + assignment.variant = Absmartly::Switchback::Assigner.assign(serving.cluster_key, period, + switchback_seed(data), data.split.length) + end + + def switchback_assignment_current?(assignment, entry, custom, override) + return assignment.overridden && assignment.variant == override unless override.nil? + return false if assignment.overridden + return false unless assignment.rule_override || custom == assignment.custom_assignment + + data = entry.data + return false unless data.id == assignment.id && data.iteration == assignment.iteration && + data.full_on_variant == assignment.full_on_variant && + data.traffic_split == assignment.traffic_split + + # Only an eligible cluster consulted its rules and audience. + assignment.serving.status != Absmartly::Switchback::Serving::ELIGIBLE || + (entry.unconditional && assignment.rule_key.equal?(NO_RULES)) || + audience_matches(entry, assignment, assignment.unit_type) + end + + # The unit a switchback with no serving unit is recorded under: the first + # linked type of a readable map, otherwise the declared unitType. + def switchback_fallback_unit_type(entry) + entry.switchback_source_paths.nil? ? entry.data.unit_type : entry.switchback_source_types[0] + end + + # Drops every slot of an experiment's epoch once its definition is gone, + # no longer a switchback, or of another generation. Caller holds + # @assignment_mutex. + def drop_switchback_epoch(name) + epoch = @switchback_epochs.delete(name) + return if epoch.nil? + + epoch.periods.each { |period| @assignment_cache.delete("#{name}#{SWITCHBACK_KEY_SEPARATOR}#{period}") } + @assignment_cache.delete(name) + end + + # At most SWITCHBACK_RETAINED_PERIODS period indices per experiment; the + # lowest one other than the period just installed is evicted. + def retain_switchback_period(name, entry, period) + epoch = (@switchback_epochs[name] ||= SwitchbackEpoch.new(entry.switchback_generation, [])) + return if period.nil? || epoch.periods.include?(period) + + epoch.periods.push(period).sort! + return if epoch.periods.length <= SWITCHBACK_RETAINED_PERIODS + + evicted = epoch.periods[0] == period ? epoch.periods[1] : epoch.periods[0] + epoch.periods.delete(evicted) + @assignment_cache.delete("#{name}#{SWITCHBACK_KEY_SEPARATOR}#{evicted}") + end + + # Test seam: the cached slot of a switchback at the clock's current reading. + def switchback_resolution_for_test(name) + @assignment_mutex.synchronize do + entry = experiment(name) + period = entry.nil? || !entry.switchback ? nil : switchback_period(entry, now_millis) + @assignment_cache[period.nil? ? name : "#{name}#{SWITCHBACK_KEY_SEPARATOR}#{period}"] + end + end + # Collector IDs are integers; integral floats and canonical decimal text # are accepted too. Other text is ignored, even when identical on both sides. def holdout_id(id) @@ -1576,8 +2152,13 @@ def init_common(clock, config, data_provider, event_handler, event_logger, @failed_marked = false @exposing = {}.compare_by_identity @exposure_condvar = ConditionVariable.new + @switchback_epochs = {} + @switchbacks_active = false + @switchback_generation = 0 + @switchback_exposures = nil @assignments = {} @clock = clock.is_a?(String) ? Time.iso8601(clock) : clock + @fixed_millis = nil @publish_delay = config.publish_delay @refresh_interval = config.refresh_interval @event_handler = event_handler @@ -1664,7 +2245,9 @@ class Assignment :traffic_split, :variant, :assigned, :overridden, :eligible, :full_on, :custom, :audience_mismatch, :variables, :exposed, :attrs_seq, :rule_override, :rule_variant, :rule_missing_unit, :rule_key, - :suppressed, :holdouts, :matched_holdouts, :holdout_assignments, :holdout_arm_count + :suppressed, :holdouts, :matched_holdouts, :holdout_assignments, :holdout_arm_count, + :switchback, :serving, :switchback_silent, :custom_assignment, :switchback_key, + :serving_read_at, :switchback_entry, :serving_units, :serving_attributes def initialize @variant = 0 @@ -1682,6 +2265,9 @@ def initialize @attrs_seq = 0 @holdouts = nil @matched_holdouts = nil + @switchback = false + @switchback_silent = false + @switchback_key = nil # Private: set by the context on an assignment built from a failed load's # empty snapshot. Initialized so every assignment keeps one layout. @failed_snapshot = false @@ -1689,7 +2275,9 @@ def initialize end class ExperimentVariables - attr_accessor :data, :variables, :rules, :rule_key, :unconditional, :holdouts + attr_accessor :data, :variables, :rules, :rule_key, :unconditional, :holdouts, + :switchback, :switchback_source_types, :switchback_source_paths, :switchback_source_roots, + :switchback_generation, :switchback_grid # Every field is set up front so all instances share one object shape and # the cached read path's attribute reads stay monomorphic. @@ -1700,6 +2288,12 @@ def initialize @rule_key = nil @unconditional = nil @holdouts = nil + @switchback = false + @switchback_source_types = nil + @switchback_source_paths = nil + @switchback_source_roots = nil + @switchback_generation = nil + @switchback_grid = nil end end diff --git a/lib/json/experiment.rb b/lib/json/experiment.rb index 4e0f4503..8911453a 100644 --- a/lib/json/experiment.rb +++ b/lib/json/experiment.rb @@ -10,7 +10,11 @@ class Experiment attr_accessor :id, :name, :unit_type, :iteration, :seed_hi, :seed_lo, :split, :traffic_seed_hi, :traffic_seed_lo, :traffic_split, :full_on_variant, :applications, :variants, :audience_strict, :audience, :custom_field_values, - :assignment_rules, :holdout_ids, :holdout_type + :assignment_rules, :holdout_ids, :holdout_type, + :randomization_type, :switchback_clusters, :switchback_cluster_values, + :switchback_start_at, :switchback_period_ms, :switchback_carryover_duration_ms, + :switchback_burn_in_duration_ms, :switchback_burn_out_duration_ms, + :switchback_design_type, :switchback_estimand ALLOWED_KEYS = %i[ id name unitType unit_type iteration seedHi seed_hi seedLo seed_lo split @@ -18,6 +22,12 @@ class Experiment fullOnVariant full_on_variant applications variants audienceStrict audience_strict audience customFieldValues custom_field_values assignmentRules assignment_rules holdoutIds holdout_ids holdoutType holdout_type + randomizationType randomization_type switchbackClusters switchback_clusters + switchbackClusterValues switchback_cluster_values switchbackStartAt switchback_start_at + switchbackPeriodMs switchback_period_ms switchbackCarryoverDurationMs switchback_carryover_duration_ms + switchbackBurnInDurationMs switchback_burn_in_duration_ms switchbackBurnOutDurationMs + switchback_burn_out_duration_ms switchbackDesignType switchback_design_type + switchbackEstimand switchback_estimand ].freeze def initialize(args = {}) @@ -71,7 +81,23 @@ def ==(o) @variants == that.variants && @audience_strict == that.audience_strict && @audience == that.audience && @custom_field_values == that.custom_field_values && @assignment_rules == that.assignment_rules && - holdout_ids == that.holdout_ids && holdout_type == that.holdout_type + holdout_ids == that.holdout_ids && holdout_type == that.holdout_type && + switchback_fields == that.switchback_fields + end + + # The switchback fields, compared in order: switchbackClusters order is + # semantic, so two maps with the same entries in another order differ. + def switchback_fields + [randomization_type, Experiment.ordered_clusters(switchback_clusters), switchback_cluster_values, + switchback_start_at, switchback_period_ms, switchback_carryover_duration_ms, + switchback_burn_in_duration_ms, switchback_burn_out_duration_ms, switchback_design_type, + switchback_estimand] + end + + # A cluster map as its ordered [type, path] pairs, with Symbol and String + # unit type names alike. + def self.ordered_clusters(clusters) + clusters.is_a?(Hash) ? clusters.map { |type, path| [type.to_s, path] } : clusters end def hash_code diff --git a/spec/absmartly_spec.rb b/spec/absmartly_spec.rb index 12089742..4f94c501 100644 --- a/spec/absmartly_spec.rb +++ b/spec/absmartly_spec.rb @@ -126,7 +126,7 @@ def clear ] end let(:clock) { Time.at(1620000000000 / 1000) } - let(:clock_in_millis) { clock.to_i } + let(:clock_in_millis) { clock.to_i * 1000 } let(:descr) { DefaultContextDataDeserializer.new } let(:json) { resource("context.json") } diff --git a/spec/context_holdouts_spec.rb b/spec/context_holdouts_spec.rb index 9afbe0c8..25890c66 100644 --- a/spec/context_holdouts_spec.rb +++ b/spec/context_holdouts_spec.rb @@ -39,7 +39,7 @@ module ContextHoldoutsSpec environments: [], variant: 1 }]) let(:clock) { Time.at(1620000000000 / 1000) } - let(:now) { clock.to_i } + let(:now) { clock.to_i * 1000 } let(:variable_parser) { DefaultVariableParser.new } let(:audience_matcher) { AudienceMatcher.new(DefaultAudienceDeserializer.new) } let(:published) { [] } @@ -811,7 +811,7 @@ def three_arm_context(seeds) refresh(context, data_of([experiment(1, "exp", holdout_ids: [11])], [holdout(11, "holdout_h", HOLDOUT_A, iteration: 2)])) - context.send(:cached_or_new_assignment, "exp", context.instance_variable_get(:@state)).tap do |current| + context.send(:cached_or_new_assignment, "exp", context.instance_variable_get(:@state), now).tap do |current| context.queue_exposure(current) end end diff --git a/spec/context_shared_variable_keys_spec.rb b/spec/context_shared_variable_keys_spec.rb index ce7388e8..2a987db6 100644 --- a/spec/context_shared_variable_keys_spec.rb +++ b/spec/context_shared_variable_keys_spec.rb @@ -655,25 +655,30 @@ def assigned(name, variant = VARIANT) expect(exposures_of(context)).to eq([assigned("holdout_a"), assigned("holdout_b"), assigned("exp_high")]) end - it "stamps a loser's holdout exposure with the read's clock" do - ticks = (1000..).step(1000).each - allow(clock).to receive(:to_i) { ticks.next } - context = create_context([strict_mismatch(1, "exp_low").merge(holdoutIds: [11]), experiment(2, "exp_high")], - holdouts: [holdout(11, "holdout_a", NOT_HOLDING_OUT)]) + # A clock that responds to call is read on every call, so each read is counted. + context "with a live clock" do + let(:ticks) { (1000..).step(1000).each } + let(:clock) { -> { ticks.next } } - context.variable_value("color", "default") - context.publish - expect(published.flat_map(&:exposures).map { |e| [e.name, e.exposed_at] }).to eq([["holdout_a", 2000], - ["exp_high", 3000]]) - end + it "stamps a loser's holdout exposure with the read's clock" do + context = create_context([strict_mismatch(1, "exp_low").merge(holdoutIds: [11]), experiment(2, "exp_high")], + holdouts: [holdout(11, "holdout_a", NOT_HOLDING_OUT)]) - it "reads the clock only for the first exposures, not on warm reads past a covered loser" do - context = create_context([strict_mismatch(1, "exp_low").merge(holdoutIds: [11]), experiment(2, "exp_high")], - holdouts: [holdout(11, "holdout_a", NOT_HOLDING_OUT)]) - context.variable_value("color", "default") + context.variable_value("color", "default") + context.publish + # 1000 is set_attribute's setAt. + expect(published.flat_map(&:exposures).map { |e| [e.name, e.exposed_at] }).to eq([["holdout_a", 2000], + ["exp_high", 3000]]) + end - expect(clock).not_to receive(:to_i) - 3.times { context.variable_value("color", "default") } + it "reads the clock only for the first exposures, not on warm reads past a covered loser" do + context = create_context([strict_mismatch(1, "exp_low").merge(holdoutIds: [11]), experiment(2, "exp_high")], + holdouts: [holdout(11, "holdout_a", NOT_HOLDING_OUT)]) + context.variable_value("color", "default") + + expect(ticks).not_to receive(:next) + 3.times { context.variable_value("color", "default") } + end end it "queues no loser holdout exposure once a logger callback closed the context" do diff --git a/spec/context_spec.rb b/spec/context_spec.rb index e7fd171d..b2e3d24e 100644 --- a/spec/context_spec.rb +++ b/spec/context_spec.rb @@ -72,7 +72,7 @@ ] } let(:clock) { Time.at(1620000000000 / 1000) } - let(:clock_in_millis) { clock.to_i } + let(:clock_in_millis) { clock.to_i * 1000 } let(:descr) { DefaultContextDataDeserializer.new } let(:json) { resource("context.json") } diff --git a/spec/context_switchback_cluster_spec.rb b/spec/context_switchback_cluster_spec.rb new file mode 100644 index 00000000..fe794a37 --- /dev/null +++ b/spec/context_switchback_cluster_spec.rb @@ -0,0 +1,1499 @@ +# frozen_string_literal: true + +require "switchback_support" + +# Ports of java-sdk ContextSwitchbackClusterTest and ContextSwitchbackClusterRuleTest +# (core-api/src/test/java/com/absmartly/sdk). Variants come from the raw key and the assigner, +# both pinned by the platform golden vectors. +module ContextSwitchbackClusterSpec + UNIT_TYPE = "store_id" + UID = "e791e240fcd3df7d238cfc285f475e8152fcc0ec" + SEED_HI = -5 + SEED_LO = -7 + # An audience the context never matches (no "tier" attribute). + STRICT_GOLD_AUDIENCE = '{"filter":[{"eq":[{"var":"tier"},{"value":"gold"}]}]}' + HOUR = SwitchbackSpecSupport::HOUR + ANCHOR = SwitchbackSpecSupport::ANCHOR + + RSpec.describe "Context switchback clusters" do + include SwitchbackSpecSupport + + ARMS = 3 + + let(:clock) { SwitchbackSpecSupport::MutableClock.new(ANCHOR) } + let(:provider) { double("ContextDataProvider") } + + def attribute_switchback(path, **extra) + { + id: 1, name: "exp_sb", unitType: UNIT_TYPE, iteration: 1, seedHi: SEED_HI, seedLo: SEED_LO, + split: Array.new(ARMS) { 1.0 / ARMS }, + variants: Array.new(ARMS) { |i| { name: ("A".ord + i).chr, config: "{\"sb.arm\":#{i}}" } }, + trafficSeedHi: 1, trafficSeedLo: 2, trafficSplit: [0.0, 1.0], fullOnVariant: 0, + applications: [{ name: "website" }], audienceStrict: false, audience: nil, + randomizationType: "switchback", switchbackClusters: { UNIT_TYPE => path }, + switchbackStartAt: ANCHOR, switchbackPeriodMs: HOUR, switchbackDesignType: "balanced_block" + }.merge(extra) + end + + def create_context(experiment, units: { UNIT_TYPE => UID }) + build_context(data_of([experiment]), units: units, provider: provider) + end + + def refresh_to(context, experiment) + allow(provider).to receive(:context_data).and_return(ready(data_of([experiment]))) + context.refresh + end + + def expected(key, period) + draw(key, period, SEED_HI, SEED_LO, ARMS) + end + + def expected_schedule(key) + (0...12).map { |i| expected(key, i) } + end + + def peek_schedule(context) + (0...12).map do |i| + clock.now = ANCHOR + i * HOUR + context.peek_treatment("exp_sb") + end + end + + def sb_exposure(variant, exposed_at, eligible, audience_mismatch) + exposure(1, "exp_sb", UNIT_TYPE, variant, exposed_at, true, eligible, false, false, false, audience_mismatch) + end + + # The Collector re-resolves the cluster from the published attributes at exposedAt, so an + # exposure must point at an instant whose attributes give the cluster the SDK served. + def collector_cluster(event, exposure, path) + selected = event.attributes.select { |a| a.name.to_s.strip == path && a.set_at <= exposure.exposed_at } + .max_by.with_index { |a, i| [a.set_at, i] } + selected&.value + end + + def expose_and_publish(context) + clock.now = ANCHOR + context.treatment("exp_sb") + context.publish + context.send(:event_handler).events.last + end + + it "never keys the cluster by the unit uid" do + context = create_context(attribute_switchback("city")) + 3.times do |i| + clock.now = ANCHOR + i * HOUR + expect(context.treatment("exp_sb")).to eq(0) + end + expect(context.pending_count).to eq(0) + end + + # A numeric uid serves and publishes as its canonical text does; the key is the attribute. + it "clusters a numeric unit uid like its canonical string" do + [[123_456_789, "123456789"], [123_456_789.0, "123456789"], [125.75, "126"]].each do |uid, text| + numeric = create_context(attribute_switchback("city"), units: { UNIT_TYPE => uid }) + clock.now = ANCHOR + numeric.set_attribute("city", "Lisboa") + numeric_event = expose_and_publish(numeric) + numeric_schedule = peek_schedule(numeric) + textual = create_context(attribute_switchback("city"), units: { UNIT_TYPE => text }) + clock.now = ANCHOR + textual.set_attribute("city", "Lisboa") + text_event = expose_and_publish(textual) + + expect(numeric_schedule).to eq(expected_schedule("Lisboa")) + expect(numeric_schedule).to eq(peek_schedule(textual)) + expect(numeric_event.units).to eq(text_event.units) + expect(numeric_event.exposures).to eq(text_event.exposures) + expect(numeric_event.units[0].uid).to eq(Hashing.hash_unit(text)) + end + end + + # Independent reference hashes, and the raw-key schedule of 123456789 as an Integer attribute. + it "matches the independent reference for numeric uids and an integer cluster value" do + schedule = [0, 2, 1, 0, 1, 2, 0, 1, 2, 2, 1, 0] + [[123_456_789, "JfnnlDI7RTiF9RgfG2JNCw"], [9_007_199_254_740_993, "OngwCmjeKhIQyeNybDy4eg"]].each do |uid, hash| + context = create_context(attribute_switchback("region"), units: { UNIT_TYPE => uid }) + clock.now = ANCHOR + context.set_attribute("region", 123_456_789) + event = expose_and_publish(context) + + # Integer uids hash from their exact decimal text, so 2**53 + 1 is its own unit here. + expect(event.units[0].uid).to eq(uid == 123_456_789 ? hash : Hashing.hash_unit("9007199254740993")) + expect(event.exposures).to eq([sb_exposure(schedule[0], ANCHOR, true, false)]) + expect(peek_schedule(context)).to eq(schedule) + end + end + + # Periods 0..11 of the raw key "Lisboa", from the independent murmur3 reference. + it "serves the raw attribute value" do + context = create_context(attribute_switchback("city")) + context.set_attribute("city", "Lisboa") + expect(peek_schedule(context)).to eq([0, 2, 1, 2, 1, 0, 1, 0, 2, 0, 1, 2]) + expect(peek_schedule(context)).to eq(expected_schedule("Lisboa")) + end + + it "shares the schedule between units sharing an attribute value" do + lisboa = create_context(attribute_switchback("city")) + lisboa.set_attribute("city", "Lisboa") + porto = create_context(attribute_switchback("city")) + porto.set_attribute("city", "Porto") + other = create_context(attribute_switchback("city"), units: { UNIT_TYPE => "another-store" }) + other.set_attribute("city", "Lisboa") + + expect(peek_schedule(lisboa)).to eq(expected_schedule("Lisboa")) + expect(peek_schedule(other)).to eq(expected_schedule("Lisboa")) + expect(peek_schedule(porto)).to eq(expected_schedule("Porto")) + expect(expected_schedule("Lisboa")).not_to eq(expected_schedule("Porto")) + end + + it "resolves nested and array paths and integer values" do + nested = create_context(attribute_switchback("geo/city")) + nested.set_attribute("geo", { "city" => "Porto" }) + expect(peek_schedule(nested)).to eq(expected_schedule("Porto")) + + clock.now = ANCHOR + symbols = create_context(attribute_switchback("geo/city")) + symbols.set_attribute(:geo, { city: :Porto }) + expect(peek_schedule(symbols)).to eq(expected_schedule("Porto")) + + clock.now = ANCHOR + array = create_context(attribute_switchback("items/1/city")) + array.set_attribute("items", [{ "city" => "Lisbon" }, { "city" => "Faro" }]) + expect(peek_schedule(array)).to eq(expected_schedule("Faro")) + + clock.now = ANCHOR + integer = create_context(attribute_switchback("region")) + integer.set_attribute("region", 42) + expect(peek_schedule(integer)).to eq(expected_schedule("42")) + + # Read through the JSON encoding the Collector sees: a Symbol is a string. + clock.now = ANCHOR + symbol = create_context(attribute_switchback("city")) + symbol.set_attribute("city", :c) + expect(peek_schedule(symbol)).to eq(expected_schedule("c")) + + # A BigDecimal (a bundled gem, not in the Gemfile, from Ruby 3.4) is published as its JSON + # text ("0.42e2"), which the Collector keys as a string. + if SwitchbackSpecSupport.big_decimal? + clock.now = ANCHOR + decimal = create_context(attribute_switchback("geo/city")) + decimal.set_attribute("geo", { "city" => BigDecimal("42") }) + expect(peek_schedule(decimal)).to eq(expected_schedule("0.42e2")) + end + + clock.now = ANCHOR + 10 + floating = create_context(attribute_switchback("city")) + floating.set_attribute("city", 2.0) + expect(floating.treatment("exp_sb")).to eq(0) + expect(floating.pending_count).to eq(0) + end + + it "makes values without a cluster key ineligible" do + [nil, "", true, false, 1.5, 2.0, 3.0, { "a" => "b" }, ["x"]].each do |value| + clock.now = ANCHOR + context = create_context(attribute_switchback("city")) + context.set_attribute("city", value) + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(0), value.inspect + expect(context.variable_value("sb.arm", -1)).to eq(0), value.inspect + expect(context.pending_count).to eq(0), value.inspect + end + + missing = create_context(attribute_switchback("geo/city")) + missing.set_attribute("geo", { "country" => "PT" }) + clock.now = ANCHOR + 10 + expect(missing.treatment("exp_sb")).to eq(0) + expect(missing.pending_count).to eq(0) + end + + # The Collector reads the published JSON text, so a UTF-16 string keys like its UTF-8 twin, for + # the draw and the allow-list. + it "keys a string by its published UTF-8 text" do + [nil, ["Zürich"]].each do |allowed| + utf8 = create_context(attribute_switchback("city", switchbackClusterValues: allowed)) + utf8.set_attribute("city", "Zürich") + utf16 = create_context(attribute_switchback("city", switchbackClusterValues: allowed)) + utf16.set_attribute("city", "Zürich".encode("UTF-16LE")) + clock.now = ANCHOR + 10 + expect(utf16.treatment("exp_sb")).to eq(expected("Zürich", 0)), allowed.inspect + expect(utf8.treatment("exp_sb")).to eq(expected("Zürich", 0)) + expect(published_exposures(utf16)).to eq(published_exposures(utf8)) + expect(utf8.pending_count).to eq(0) + end + expect(expected("Zürich", 0)).not_to eq(0) + + binary = create_context(attribute_switchback("city")) + binary.set_attribute("city", "Zürich".b) + expect(binary.treatment("exp_sb")).to eq(expected("Zürich", 0)) + + invalid = create_context(attribute_switchback("city")) + invalid.set_attribute("city", "\xFF".b) + expect(invalid.treatment("exp_sb")).to eq(0) + expect(invalid.pending_count).to eq(0) + end + + it "makes values without a JSON encoding ineligible" do + cyclic = {} + cyclic["self"] = cyclic + [cyclic, [Float::NAN], { "city" => Float::INFINITY }].each do |value| + context = create_context(attribute_switchback("geo/city")) + context.set_attribute("geo", value) + expect(context.treatment("exp_sb")).to eq(0) + expect(context.pending_count).to eq(0) + end + end + + it "makes unservable configurations ineligible" do + experiments = ["items/0", "items/-1/city", "", "geo.city", "'city", "\"city", nil, 7].map do |path| + attribute_switchback("city", switchbackClusters: { UNIT_TYPE => path }) + end + experiments << attribute_switchback("city", switchbackPeriodMs: nil) + experiments << attribute_switchback("city", switchbackPeriodMs: 0) + experiments << attribute_switchback("city", switchbackPeriodMs: -HOUR) + experiments << attribute_switchback("city", switchbackPeriodMs: 1.5 * HOUR) + experiments << attribute_switchback("city", split: [1.0], variants: [{ name: "A", config: nil }]) + experiments << attribute_switchback("city", switchbackClusters: "store_id") + experiments << attribute_switchback("city", switchbackClusters: [[UNIT_TYPE, "city"]]) + experiments.each do |experiment| + clock.now = ANCHOR + context = create_context(experiment) + context.set_attribute("city", "Lisboa") + context.set_attribute("items", [{ "city" => "Lisbon" }]) + 3.times do |i| + clock.now = ANCHOR + i * HOUR + expect(context.treatment("exp_sb")).to eq(0), experiment.inspect + end + expect(context.pending_count).to eq(0), experiment.inspect + end + end + + # The legacy path: a unit of the declared unitType only identifies an ineligible control; + # without one the experiment does not apply. + it "makes a missing or empty cluster map only a legacy ineligible control" do + [nil, {}].each do |clusters| + context = create_context(attribute_switchback("city", switchbackClusters: clusters)) + context.set_attribute("city", "Lisboa") + expect(context.treatment("exp_sb")).to eq(0) + expect(context.variable_value("sb.arm", -1)).to eq(0) + expect(context.pending_count).to eq(0) + + other = create_context(attribute_switchback("city", switchbackClusters: clusters), units: { "user_id" => "u1" }) + other.set_attribute("city", "Lisboa") + expect(other.treatment("exp_sb")).to eq(0) + expect(other.variable_value("sb.arm", -1)).to eq(-1) + expect(other.pending_count).to eq(0) + end + end + + it "uses the latest attribute set at or before the resolution instant" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 2 * HOUR + context.set_attribute("city", "Porto") + clock.now = ANCHOR + 4 * HOUR + context.set_attribute("city", "Lisboa") + + clock.now = ANCHOR + HOUR + expect(context.peek_treatment("exp_sb")).to eq(0) + clock.now = ANCHOR + 3 * HOUR + expect(context.peek_treatment("exp_sb")).to eq(expected("Porto", 3)) + clock.now = ANCHOR + 4 * HOUR + expect(context.peek_treatment("exp_sb")).to eq(expected("Lisboa", 4)) + end + + # Lisboa and Faro draw different variants in period 0, so the winner is visible. + it "breaks a setAt tie with the attribute set last" do + expect(expected("Lisboa", 0)).not_to eq(expected("Faro", 0)) + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 5 + context.set_attribute("city", "Faro") + context.set_attribute("city", "Lisboa") + expect(context.peek_treatment("exp_sb")).to eq(expected("Lisboa", 0)) + + other = create_context(attribute_switchback("city")) + other.set_attribute("city", "Lisboa") + other.set_attribute("city", "Faro") + expect(other.peek_treatment("exp_sb")).to eq(expected("Faro", 0)) + end + + it "matches attribute names with surrounding spaces trimmed" do + context = create_context(attribute_switchback("city")) + context.set_attribute(" city ", "Faro") + expect(context.peek_treatment("exp_sb")).to eq(expected("Faro", 0)) + end + + it "never reads the application or environment system attributes" do + context = create_context(attribute_switchback("environment")) + expect(context.treatment("exp_sb")).to eq(0) + expect(context.pending_count).to eq(0) + end + + it "does not reassign within the period after a mid-period setAttribute" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + + clock.now = ANCHOR + 20 + context.set_attribute("city", "Porto") + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + expect(context.peek_treatment("exp_sb")).to eq(expected("Lisboa", 0)) + expect(context.pending_count).to eq(1) + + differing = 0 + (1...12).each do |i| + clock.now = ANCHOR + i * HOUR + expect(context.treatment("exp_sb")).to eq(expected("Porto", i)) + differing += 1 if expected("Porto", i) != expected("Lisboa", i) + end + expect(differing).not_to eq(0) + expect(context.pending_count).to eq(12) + end + + it "waits for the next period after an ineligible resolution" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(0) + context.set_attribute("city", "Lisboa") + clock.now = ANCHOR + 20 + expect(context.treatment("exp_sb")).to eq(0) + expect(context.pending_count).to eq(0) + + clock.now = ANCHOR + HOUR + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 1)) + expect(published_exposures(context)).to eq([sb_exposure(expected("Lisboa", 1), ANCHOR + HOUR, true, false)]) + end + + it "keeps the period's key across traffic changes within the period" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + + clock.now = ANCHOR + 20 + context.set_attribute("city", "Porto") + refresh_to(context, attribute_switchback("city", trafficSplit: [1.0, 0.0])) + expect(context.treatment("exp_sb")).to eq(0) + + refresh_to(context, attribute_switchback("city")) + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + expect(context.pending_count).to eq(3) + + clock.now = ANCHOR + HOUR + expect(context.treatment("exp_sb")).to eq(expected("Porto", 1)) + end + + # The cluster is resolved before traffic: a miss is recorded, and traffic restored later in + # the period serves the key read first. + it "keeps the key when traffic is restored within the period" do + context = create_context(attribute_switchback("city", trafficSplit: [1.0, 0.0])) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Faro") + expect(context.treatment("exp_sb")).to eq(0) + + clock.now = ANCHOR + 20 + context.set_attribute("city", "Lisboa") + refresh_to(context, attribute_switchback("city")) + expect(expected("Faro", 0)).to eq(1) + expect(context.treatment("exp_sb")).to eq(expected("Faro", 0)) + # The second exposure keeps the Faro key: at ANCHOR + 20 the batch's city is Lisboa, so it is + # published in a body of its own with the attributes its slot read, at its own instant. + expect(published_exposures(context)).to eq([sb_exposure(0, ANCHOR + 10, false, false), + sb_exposure(expected("Faro", 0), ANCHOR + 20, true, false)]) + separate = context.send(:event_handler).events.last + expect(collector_cluster(separate, separate.exposures[0], "city")).to eq("Faro") + end + + # An audience change re-resolves the slot (a new exposure) but keeps its key. + it "keeps the period's key when the audience is re-evaluated" do + context = create_context(attribute_switchback("city", audience: STRICT_GOLD_AUDIENCE)) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + context.set_attribute("tier", "gold") + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + + clock.now = ANCHOR + 20 + context.set_attribute("city", "Porto") + context.set_attribute("tier", "silver") + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + + # At ANCHOR + 20 the batch's city is Porto, so the second exposure goes in its own body. + expect(published_exposures(context)).to eq([sb_exposure(expected("Lisboa", 0), ANCHOR + 10, true, false), + sb_exposure(expected("Lisboa", 0), ANCHOR + 20, true, true)]) + separate = context.send(:event_handler).events.last + expect(collector_cluster(separate, separate.exposures[0], "city")).to eq("Lisboa") + end + + it "keeps a missing key through an audience re-evaluation" do + context = create_context(attribute_switchback("city", audience: STRICT_GOLD_AUDIENCE)) + clock.now = ANCHOR + 10 + context.set_attribute("tier", "gold") + expect(context.treatment("exp_sb")).to eq(0) + + clock.now = ANCHOR + 20 + context.set_attribute("city", "Faro") + context.set_attribute("tier", "silver") + expect(expected("Faro", 0)).to eq(1) + expect(context.treatment("exp_sb")).to eq(0) + expect(context.pending_count).to eq(0) + + clock.now = ANCHOR + HOUR + expect(context.peek_treatment("exp_sb")).to eq(expected("Faro", 1)) + clock.now = ANCHOR + 2 * HOUR + expect(expected("Faro", 2)).to eq(2) + expect(context.peek_treatment("exp_sb")).to eq(expected("Faro", 2)) + end + + it "publishes attributes that give the served cluster at exposedAt after a peek and a change" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + expect(context.peek_treatment("exp_sb")).to eq(expected("Lisboa", 0)) + clock.now = ANCHOR + 20 + context.set_attribute("city", "Faro") + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + expect(expected("Faro", 0)).not_to eq(expected("Lisboa", 0)) + + context.publish + events = context.send(:event_handler).events + expect(events.length).to eq(1) + expect(events[0].exposures.map(&:exposed_at)).to eq([ANCHOR + 20]) + expect(collector_cluster(events[0], events[0].exposures[0], "city")).to eq("Lisboa") + expect(events[0].attributes.map(&:value)).to eq(%w[Lisboa]) + end + + # The batch's attributes would give Faro at the exposure's instant after a rewind: the exposure + # keeps its instant (no move across a burn window) and is published with what its slot read. + it "publishes the served cluster after a clock rewind, at the exposing call's instant" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + clock.now = ANCHOR + 30 + expect(context.peek_treatment("exp_sb")).to eq(expected("Lisboa", 0)) + clock.now = ANCHOR + 20 + context.set_attribute("city", "Faro") + clock.now = ANCHOR + 40 + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + + context.publish + events = context.send(:event_handler).events + exposure = events.flat_map { |e| e.exposures || [] }.first + body = events.find { |e| (e.exposures || []).include?(exposure) } + expect(exposure.exposed_at).to eq(ANCHOR + 40) + expect(collector_cluster(body, exposure, "city")).to eq("Lisboa") + end + + # The read saw an attribute stamped after the exposure's instant (the clock stepped back between + # them): the separate body carries the read's attributes stamped at exposedAt. + it "publishes the served cluster when the read's attribute is later than exposedAt" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 30 + context.set_attribute("city", "Lisboa") + expect(context.peek_treatment("exp_sb")).to eq(expected("Lisboa", 0)) + clock.now = ANCHOR + 20 + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + + context.publish + body = context.send(:event_handler).events.last + expect(body.exposures.map(&:exposed_at)).to eq([ANCHOR + 20]) + expect(collector_cluster(body, body.exposures[0], "city")).to eq("Lisboa") + expect(body.attributes.map { |a| [a.value, a.set_at] }).to eq([["Lisboa", ANCHOR + 20]]) + end + + # The fallback keeps every captured attribute, unrelated ones included; only the cluster-source + # attribute the read selected is stamped at exposedAt. + it "keeps unrelated attributes in the rewind fallback body" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 5 + context.set_attribute("tier", "gold") + clock.now = ANCHOR + 30 + context.set_attribute("city", "Lisboa") + clock.now = ANCHOR + 31 + context.set_attribute("plan", "pro") + expect(context.peek_treatment("exp_sb")).to eq(expected("Lisboa", 0)) + clock.now = ANCHOR + 20 + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + clock.now = ANCHOR + 25 + context.set_attribute("city", "Faro") + + context.publish + body = context.send(:event_handler).events.last + expect(body.exposures.map(&:exposed_at)).to eq([ANCHOR + 20]) + expect(collector_cluster(body, body.exposures[0], "city")).to eq("Lisboa") + # An unrelated attribute keeps its own setAt, even one later than exposedAt. + expect(body.attributes.map { |a| [a.name, a.value, a.set_at] }) + .to eq([["tier", "gold", ANCHOR + 5], ["city", "Lisboa", ANCHOR + 20], ["plan", "pro", ANCHOR + 31]]) + end + + # A later value of a cluster-source attribute that the read skipped (it was in the read's future + # after a rewind) is left out of the fallback body, so the Collector keeps the served cluster. + # A selected attribute already earlier than exposedAt keeps its setAt. + it "drops a later cluster-source value the read skipped from the fallback body" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + clock.now = ANCHOR + 50 + context.set_attribute("city", "Faro") + clock.now = ANCHOR + 30 + expect(context.peek_treatment("exp_sb")).to eq(expected("Lisboa", 0)) + clock.now = ANCHOR + 60 + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + + context.publish + body = context.send(:event_handler).events.last + expect(body.exposures.map(&:exposed_at)).to eq([ANCHOR + 60]) + expect(collector_cluster(body, body.exposures[0], "city")).to eq("Lisboa") + expect(body.attributes.map { |a| [a.name, a.value, a.set_at] }).to eq([["city", "Lisboa", ANCHOR + 10]]) + end + + # The drop rule matches cluster-source names trimmed, as the Collector does, and covers every + # declared source: a later " city " value and a later zone value are both left out. + it "drops later values of every cluster source, matched by trimmed name, from the fallback body" do + sources = { UNIT_TYPE => "city", "user_id" => "zone" } + context = create_context(attribute_switchback("city", switchbackClusters: sources), + units: { UNIT_TYPE => UID, "user_id" => "u-1" }) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + context.set_attribute("zone", "Lisboa") + clock.now = ANCHOR + 50 + context.set_attribute(" city ", "Faro") + context.set_attribute("zone", "Porto") + clock.now = ANCHOR + 30 + expect(context.peek_treatment("exp_sb")).to eq(expected("Lisboa", 0)) + clock.now = ANCHOR + 60 + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + + context.publish + body = context.send(:event_handler).events.last + expect(body.attributes.map { |a| [a.name.strip, a.value] }).to eq([%w[city Lisboa], %w[zone Lisboa]]) + end + + # The exposure is not moved to the slot's read instant, so a burn-in window that the exposing + # call is outside of keeps it in the analysis. + it "keeps an exposure outside burn-in after a mid-period change" do + context = create_context(attribute_switchback("city", switchbackBurnInDurationMs: 60_000)) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + context.peek_treatment("exp_sb") + clock.now = ANCHOR + 120_000 + context.set_attribute("city", "Faro") + clock.now = ANCHOR + 180_000 + context.treatment("exp_sb") + context.publish + events = context.send(:event_handler).events + exposure = events.flat_map { |e| e.exposures || [] }.first + expect(exposure.exposed_at).to eq(ANCHOR + 180_000) + expect(collector_cluster(events.last, exposure, "city")).to eq("Lisboa") + end + + # The Collector re-selects the serving unit from the batch's units: a unit added after the + # exposure must not move it or drop it. + it "publishes an exposure with the units it was served under after a later set_unit" do + sources = { "user_id" => "tier", UNIT_TYPE => "city" } + context = create_context(attribute_switchback("city", switchbackClusters: sources)) + clock.now = ANCHOR + 10 + context.set_attribute("tier", "1") + context.set_attribute("city", "0") + expect(context.treatment("exp_sb")).to eq(expected("0", 0)) + context.set_unit("user_id", "u-1") + context.track("goal") + context.publish + + events = context.send(:event_handler).events + separate = events.find { |e| e.exposures&.any? } + expect(separate.units.map(&:type)).to eq([UNIT_TYPE]) + expect(separate.exposures.map(&:unit)).to eq([UNIT_TYPE]) + expect(collector_cluster(separate, separate.exposures[0], "city")).to eq("0") + # Collector-equivalent selection over the body: only store_id is linked and present. + body_units = separate.units.to_h { |u| [u.type, u.uid] } + expect(sources.keys.select { |type| body_units.key?(type) }).to eq([UNIT_TYPE]) + goals = events.find { |e| e.goals&.any? } + expect(goals.units.map(&:type)).to contain_exactly(UNIT_TYPE, "user_id") + expect(context.pending_count).to eq(0) + end + + # A recorded traffic miss is checked the same way: the Collector resolves its cluster too. + it "publishes a traffic miss with the cluster it was read with after a mid-period change" do + context = create_context(attribute_switchback("city", trafficSplit: [1.0, 0.0])) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + context.peek_treatment("exp_sb") + clock.now = ANCHOR + 20 + context.set_attribute("city", "Faro") + expect(context.treatment("exp_sb")).to eq(0) + context.publish + body = context.send(:event_handler).events.last + expect(body.exposures.map(&:eligible)).to eq([false]) + expect(collector_cluster(body, body.exposures[0], "city")).to eq("Lisboa") + end + + def multi_request_context + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + context.treatment("exp_sb") + context.set_unit("user_id", "u-1") + # A same-millisecond change forces a separate switchback body; the goal is the first body. + context.set_attribute("city", "Faro") + context.track("goal") + context + end + + it "retries only the undelivered request after a later request raises" do + context = multi_request_context + publisher = context.send(:event_handler) + delivered = [] + attempts = 0 + allow(publisher).to receive(:publish) do |_ctx, event| + attempts += 1 + raise "second request failed" if attempts == 2 + + delivered << event + nil + end + expect { context.publish }.to raise_error("second request failed") + expect(delivered.length).to eq(1) + expect(delivered.first.goals.map(&:name)).to eq(["goal"]) + expect(context.pending_count).to eq(1) + context.publish + expect(delivered.length).to eq(2) + expect(delivered.last.exposures.map(&:name)).to eq(["exp_sb"]) + # The retried exposure keeps its own request and the cluster it was served. + expect(collector_cluster(delivered.last, delivered.last.exposures.first, "city")).to eq("Lisboa") + expect(context.pending_count).to eq(0) + end + + it "logs the error a raising publisher raises before it propagates, on both paths" do + [false, true].each do |multi| + context = multi ? multi_request_context : create_context(attribute_switchback("city")) + context.track("goal") unless multi + errors = [] + logger = double("logger") + allow(logger).to receive(:handle_event) { |type, data| errors << data if type == ContextEventLogger::EVENT_TYPE::ERROR } + context.send(:event_logger=, logger) + allow(context.send(:event_handler)).to receive(:publish).and_raise(StandardError, "collector down") + expect { context.publish }.to raise_error("collector down") + expect(errors).to eq(["collector down"]), multi.to_s + end + end + + # The Collector records every request attribute with an exposure, so a separate body keeps + # the attributes that are not cluster paths too. + it "keeps non-cluster attributes in a separate body" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 5 + context.set_attribute("city", "Porto") + clock.now = ANCHOR + 10 + context.set_attribute("tier", "gold") + context.set_attribute("city", "Lisboa") + context.treatment("exp_sb") + context.set_attribute("city", "Faro") + context.publish + body = context.send(:event_handler).events.last + # Without a rewind the body is every attribute the read saw, earlier cluster values included. + expect(body.attributes.map { |a| [a.name, a.value] }).to eq([%w[city Porto], %w[tier gold], %w[city Lisboa]]) + expect(collector_cluster(body, body.exposures.first, "city")).to eq("Lisboa") + end + + # A caller that changes its own String in place after the read does not change the cluster the + # slot served or the attribute published with its exposure. + it "keeps the served cluster when the caller mutates the String it set" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 10 + city = +"Lisboa" + context.set_attribute("city", city) + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + city.replace("Faro") + expect(expected("Faro", 0)).not_to eq(expected("Lisboa", 0)) + + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + context.publish + body = context.send(:event_handler).events.last + expect(collector_cluster(body, body.exposures[0], "city")).to eq("Lisboa") + expect(body.attributes.map(&:value)).to eq(%w[Lisboa]) + end + + # The same for a nested value: the Hash the caller set is copied, a shared child once. + it "keeps the served cluster when the caller mutates the Hash it set" do + context = create_context(attribute_switchback("geo/city")) + clock.now = ANCHOR + 10 + shared = { "name" => +"x" } + geo = { "city" => +"Lisboa", "a" => shared, "b" => shared } + context.set_attribute("geo", geo) + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + geo["city"] = "Faro" + shared["name"] << "y" + expect(expected("Lisboa", 0)).not_to eq(expected("Faro", 0)) + + context.publish + body = context.send(:event_handler).events.last + value = body.attributes[0].value + expect(value["city"]).to eq("Lisboa") + expect(value["a"]).to equal(value["b"]) + expect(value["a"]).to eq({ "name" => "x" }) + expect(body.exposures.length).to eq(1) + end + + # A set_attribute that lands after the batch's attributes were checked (another thread, same + # millisecond, so it would win the Collector's setAt tie) stays out of the checked body. + it "publishes the batch body its switchback exposures were checked against" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + allow(context).to receive(:separate_switchback_exposures).and_wrap_original do |original, *args| + original.call(*args).tap { context.set_attribute("city", "Faro") } + end + + context.publish + events = context.send(:event_handler).events + expect(events.length).to eq(1) + expect(events[0].attributes.map(&:value)).to eq(%w[Lisboa]) + expect(collector_cluster(events[0], events[0].exposures[0], "city")).to eq("Lisboa") + end + + # An Array value is copied too, and a subclass and a default proc stay as set. + it "keeps the served cluster when the caller mutates the Array it set" do + context = create_context(attribute_switchback("cities/0/name")) + clock.now = ANCHOR + 10 + cities = [{ "name" => "Lisboa" }] + context.set_attribute("cities", cities) + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + cities[0]["name"] = "Faro" + + context.publish + body = context.send(:event_handler).events.last + expect(body.exposures.length).to eq(1) + expect(collector_cluster(body, body.exposures[0], "cities")).to eq([{ "name" => "Lisboa" }]) + end + + it "copies a cluster value without losing its class or default proc" do + subclass = Class.new(Hash) + geo = subclass.new { |_, key| "default-#{key}" } + geo["city"] = +"Lisboa" + context = create_context(attribute_switchback("geo/city")) + clock.now = ANCHOR + 10 + context.set_attribute("geo", geo) + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + geo["city"] = "Faro" + + context.publish + value = context.send(:event_handler).events.last.attributes[0].value + expect(value).to be_a(subclass) + expect(value["missing"]).to eq("default-missing") + end + + # A subclass whose []= rewrites keys (an indifferent-access Hash) is copied without going + # through []=, and one that dup does not copy or whose copy raises is used as set; none fails the read. + it "serves a cluster from Hash subclasses that rewrite keys or cannot be copied" do + symbolizing = Class.new(Hash) do + def []=(key, value) + super(key.to_s.to_sym, value) + end + end + undupable = Class.new(Hash) do + def dup + raise "no dup" + end + end + self_dup = Class.new(Hash) do + def dup + self + end + end + raising_replace = Class.new(Hash) do + def transform_values! + raise "no replace" + end + end + [symbolizing, undupable, self_dup, raising_replace].each do |klass| + geo = klass.new + city = +"Lisboa" + geo.store("city", city) + context = create_context(attribute_switchback("geo/city")) + clock.now = ANCHOR + 10 + context.set_attribute("geo", geo) + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + expect(context.pending_count).to eq(1) + # The caller's object is never changed by the copy. + expect(geo.fetch("city")).to equal(city) + end + end + + # A slot rebuilt within its period (here by a custom assignment) keeps the period's snapshot. + it "keeps the period's snapshot when the slot is rebuilt within the period" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 10 + city = +"Lisboa" + context.set_attribute("city", city) + expect(context.peek_treatment("exp_sb")).to eq(expected("Lisboa", 0)) + city.replace("Faro") + context.set_custom_assignment("exp_sb", 2) + expect(context.treatment("exp_sb")).to eq(2) + + context.publish + body = context.send(:event_handler).events.last + expect(body.exposures.length).to eq(1) + expect(collector_cluster(body, body.exposures[0], "city")).to eq("Lisboa") + end + + # The cluster value is copied whatever name form set it: a Symbol, or one with spaces trimmed. + it "copies a cluster value set under a Symbol or a padded name" do + [:city, " city "].each do |name| + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 10 + city = +"Lisboa" + context.set_attribute(name, city) + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + city.replace("Faro") + + context.publish + body = context.send(:event_handler).events.last + expect(body.exposures.length).to eq(1) + expect(collector_cluster(body, body.exposures[0], "city")).to eq("Lisboa") + end + end + + # Nesting deeper than a cluster path reads is kept as is rather than copied without bound. + it "serves a cluster from a value nested deeper than a path reads" do + deep = [+"Lisboa"] + 10_000.times { deep = [deep] } + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 10 + context.set_attribute("deep", deep) + context.set_attribute("city", "Lisboa") + context.set_attribute("city", deep) + expect { context.treatment("exp_sb") }.not_to raise_error + end + + # Only cluster-source attributes are copied; others are published as the caller set them. + it "does not copy attributes that are not cluster sources" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 10 + tier = +"gold" + context.set_attribute("tier", tier) + context.set_attribute("city", +"Lisboa") + context.treatment("exp_sb") + snapshot = context.send(:assignment_cache).values.find(&:switchback).serving_attributes + expect(snapshot[0].value).to equal(tier) + expect(snapshot[1].value).not_to equal(context.send(:attributes)[1].value) + end + + # A set_unit that lands after the batch's units were checked stays out of the checked body. + it "publishes the batch units its switchback exposures were checked against" do + context = create_context(attribute_switchback("city", switchbackClusters: { UNIT_TYPE => "city", "user_id" => "ucity" })) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + context.set_attribute("ucity", "Faro") + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + allow(context).to receive(:separate_switchback_exposures).and_wrap_original do |original, *args| + original.call(*args).tap { context.set_unit("user_id", "u1") } + end + + context.publish + events = context.send(:event_handler).events + expect(events.length).to eq(1) + expect(events[0].units.map(&:type)).to eq([UNIT_TYPE]) + end + + # A custom assignment is part of the slot, so repeated reads in a period expose once. + it "exposes a custom-assigned switchback once per period" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + context.set_custom_assignment("exp_sb", 2) + 3.times { expect(context.treatment("exp_sb")).to eq(2) } + expect(context.variable_value("sb.arm", -1)).to eq(2) + expect(context.pending_count).to eq(1) + expect(published_exposures(context).map(&:variant)).to eq([2]) + end + + # An override is published under the unit that serves the cluster, not the first linked type. + it "publishes an override under the serving unit" do + experiment = attribute_switchback("city", switchbackClusters: { UNIT_TYPE => "city", "device_id" => "dcity" }) + context = build_context(data_of([experiment]), units: { "device_id" => "d1" }, provider: provider, + overrides: { "exp_sb" => 1 }) + clock.now = ANCHOR + 10 + context.set_attribute("dcity", "Lisboa") + expect(context.treatment("exp_sb")).to eq(1) + expect(published_exposures(context)).to eq([exposure(1, "exp_sb", "device_id", 1, ANCHOR + 10, false, true, true)]) + end + + # A switchback is separated out of a batch that also holds an ordinary exposure. + it "separates a switchback out of a batch with another exposure" do + unit = attribute_switchback("city", id: 2, name: "exp_unit", randomizationType: nil, + switchbackClusters: nil, switchbackStartAt: nil) + context = build_context(data_of([attribute_switchback("city"), unit]), units: { UNIT_TYPE => UID }) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + context.peek_treatment("exp_sb") + clock.now = ANCHOR + 20 + context.set_attribute("city", "Faro") + clock.now = ANCHOR + 30 + context.treatment("exp_sb") + context.treatment("exp_unit") + context.publish + events = context.send(:event_handler).events + expect(events.length).to eq(2) + expect(events.map { |e| e.exposures.map(&:name) }).to eq([%w[exp_unit], %w[exp_sb]]) + expect(events.first.attributes.map(&:value)).to eq(%w[Lisboa Faro]) + expect(collector_cluster(events.last, events.last.exposures.first, "city")).to eq("Lisboa") + end + + # Only an eligible cluster's exposure is separated; an override with no cluster stays in the + # batch, with the attributes set after it, even when the clock stepped back. + it "keeps an overridden exposure without a cluster in the batch" do + context = build_context(data_of([attribute_switchback("city")]), units: { UNIT_TYPE => UID }, + overrides: { "exp_sb" => 1 }) + clock.now = ANCHOR + 20 + context.treatment("exp_sb") + clock.now = ANCHOR + 10 + context.set_attribute("city", "Faro") + context.publish + events = context.send(:event_handler).events + expect(events.length).to eq(1) + expect(events.first.attributes.map(&:value)).to eq(%w[Faro]) + end + + it "stops at the first failed request and keeps all undelivered events" do + context = multi_request_context + publisher = context.send(:event_handler) + failure = StandardError.new("first request failed") + allow(publisher).to receive(:publish).and_return(failure) + expect(context.publish).to equal(failure) + expect(publisher).to have_received(:publish).once + expect(context.pending_count).to eq(2) + end + + it "logs each successful publish in order and clears switchback tracking" do + context = multi_request_context + logged = [] + logger = double("logger") + allow(logger).to receive(:handle_event) { |type, event| logged << [type, event] } + context.send(:event_logger=, logger) + context.publish + expect(logged.map(&:first)).to eq([ContextEventLogger::EVENT_TYPE::PUBLISH] * 2) + expect(logged[0][1].goals.map(&:name)).to eq(["goal"]) + expect(logged[1][1].exposures.map(&:name)).to eq(["exp_sb"]) + expect(context.instance_variable_get(:@switchback_exposures)).to be_nil + allow(context).to receive(:served_at?).and_call_original + context.track("next") + context.publish + expect(context).not_to have_received(:served_at?) + expect(context.pending_count).to eq(0) + end + + it "returns ordinary publishes to the one-request fast path after switchback delivery" do + context = multi_request_context + context.publish + allow(context).to receive(:separate_switchback_exposures).and_call_original + allow(context).to receive(:dequeue_published).and_call_original + context.track("ordinary") + context.publish + expect(context).not_to have_received(:separate_switchback_exposures) + expect(context).not_to have_received(:dequeue_published) + end + + it "preserves the serving unit when a newly added higher priority unit agrees" do + sources = { "user_id" => "tier", UNIT_TYPE => "city" } + context = create_context(attribute_switchback("city", switchbackClusters: sources)) + clock.now = ANCHOR + 10 + context.set_attribute("tier", "Lisboa") + context.set_attribute("city", "Lisboa") + context.treatment("exp_sb") + context.set_unit("user_id", "u-1") + context.publish + body = context.send(:event_handler).events.last + expect(body.units.map(&:type)).to eq([UNIT_TYPE]) + expect(body.exposures.map(&:unit)).to eq([UNIT_TYPE]) + expect(collector_cluster(body, body.exposures.first, "city")).to eq("Lisboa") + end + + # Exposures the batch already attributes correctly share one body. + it "keeps one publish body when every exposure resolves from the batch" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + context.treatment("exp_sb") + context.track("goal") + context.publish + expect(context.send(:event_handler).events.length).to eq(1) + end + + # The exposing call's own instant is kept while the attributes still give the slot's cluster. + it "keeps the exposing call's instant when the attributes are unchanged" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + context.peek_treatment("exp_sb") + clock.now = ANCHOR + 20 + context.treatment("exp_sb") + expect(published_exposures(context).map(&:exposed_at)).to eq([ANCHOR + 20]) + end + + # Attributes keep their real setAt, as in java-sdk: shifting a write past a same-millisecond + # cluster read would hide it from every other read in that millisecond (and, with a fixed + # clock, for good). A write in the exposure's own millisecond ties at the Collector, which + # takes the later entry; the next period serves the new value. + it "keeps the real setAt of an attribute written in an exposure's millisecond" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + context.set_attribute("city", "Faro") + expect(context.send(:attributes).map(&:set_at)).to eq([ANCHOR + 10, ANCHOR + 10]) + + clock.now = ANCHOR + HOUR + expect(context.treatment("exp_sb")).to eq(expected("Faro", 1)) + end + + # A read in the same millisecond as a write sees it, whatever was read before. + it "lets every read in a millisecond see an attribute set in it" do + other = attribute_switchback("city", id: 2, name: "exp_other") + context = build_context(data_of([attribute_switchback("zone", name: "exp_first"), other]), units: { UNIT_TYPE => UID }) + clock.now = ANCHOR + 10 + context.set_attribute("zone", "z") + context.peek_treatment("exp_first") + context.set_attribute("city", "Faro") + expect(context.treatment("exp_other")).to eq(expected("Faro", 0)) + expect(context.pending_count).to eq(1) + end + + it "re-resolves the period when the cluster path changes" do + context = create_context(attribute_switchback("city")) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + context.set_attribute("geo", { "city" => "Porto" }) + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + expect(context.pending_count).to eq(1) + + refresh_to(context, attribute_switchback("city")) + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + expect(context.pending_count).to eq(1) + + refresh_to(context, attribute_switchback("geo/city")) + expect(context.treatment("exp_sb")).to eq(expected("Porto", 0)) + expect(context.pending_count).to eq(2) + + refresh_to(context, attribute_switchback("geo/city", switchbackClusterValues: %w[Porto Faro])) + expect(context.treatment("exp_sb")).to eq(expected("Porto", 0)) + expect(context.pending_count).to eq(3) + end + + it "re-keys the period and moves the exposure unit when the linked unit type changes" do + context = create_context(attribute_switchback("city"), units: { UNIT_TYPE => UID, "user_id" => "user-0002" }) + clock.now = ANCHOR + 1 + context.set_attribute("city", "Lisboa") + context.set_attribute("ucity", "Faro") + expect(context.treatment("exp_sb")).to eq(expected("Lisboa", 0)) + + refresh_to(context, attribute_switchback("ucity", switchbackClusters: { "user_id" => "ucity" })) + expect(context.treatment("exp_sb")).to eq(expected("Faro", 0)) + expect(published_exposures(context).map(&:unit)).to eq([UNIT_TYPE, "user_id"]) + end + + it "applies a custom assignment only to units with a cluster key" do + keyed = create_context(attribute_switchback("city")) + keyed.set_attribute("city", "Lisboa") + keyed.set_custom_assignment("exp_sb", 2) + expect(keyed.treatment("exp_sb")).to eq(2) + + unkeyed = create_context(attribute_switchback("city")) + unkeyed.set_custom_assignment("exp_sb", 2) + expect(unkeyed.treatment("exp_sb")).to eq(0) + end + + # Inertness: a unit experiment carrying every switchback field serves and publishes exactly + # what the same experiment without them does. + it "ignores cluster fields on unit experiments" do + [nil, "unit"].each do |type| + split_rule = '{"rules":[{"type":"split","environments":[],"percentages":"34/33/33"}]}' + unit = attribute_switchback("city", randomizationType: type, + switchbackClusters: { "user_id" => "city", UNIT_TYPE => "'x" }, + switchbackClusterValues: ["nothing"], switchbackPeriodMs: 0, + assignmentRules: split_rule) + reference = unit.reject { |key, _| key.to_s.start_with?("switchback") } + published = [unit, reference].map do |experiment| + clock.now = ANCHOR - HOUR + context = create_context(experiment, units: { UNIT_TYPE => UID, "user_id" => "u" }) + context.set_attribute("city", "Lisboa") + first = context.treatment("exp_sb") + (1...6).each do |i| + clock.now = ANCHOR - HOUR + i * HOUR + expect(context.treatment("exp_sb")).to eq(first) + end + published_exposures(context) + end + expect(published[0].length).to eq(1) + expect(published[0][0].eligible).to be(true) + expect(published[0][0].rule_override).to be(true) + expect(published[0][0].exposed_at).to eq(ANCHOR - HOUR) + expect(published[0]).to eq(published[1]) + end + end + end + + # Port of the Collector's ContextAPISwitchbackTest ClusterRule section (absmartly/abs + # 9bd2b5ca35) through the public Context API, as java-sdk ContextSwitchbackClusterRuleTest + # does: switchback "sbc" (id 900, 34/33/33, 1h) linked to user_id at "profile/store" and to + # session_id at "session_store", declared session_id first (unit type id order) although the + # user_id link was added first. A context holds one uid per unit type, so the declared source + # order alone decides which unit serves. + RSpec.describe "Context switchback cluster rules" do + include SwitchbackSpecSupport + + PERIOD = 5 + NOW = ANCHOR + PERIOD * HOUR + 17 * 60_000 + RULE_SEED_HI = 0x1234 + RULE_SEED_LO = 0x5678abcd + RULE_TRAFFIC_SEED_HI = 7 + RULE_TRAFFIC_SEED_LO = 11 + SESSION = "session_id" + USER = "user_id" + + let(:clock) { SwitchbackSpecSupport::MutableClock.new(NOW) } + let(:links) { [[USER, "profile/store"], [SESSION, "session_store"]] } + let(:extra) { {} } + + def switchback_experiment(name, id, unit_type, split) + parts = split.split("/").map { |p| Integer(p) / 100.0 } + { + id: id, name: name, unitType: unit_type, iteration: 1, seedHi: RULE_SEED_HI, seedLo: RULE_SEED_LO, split: parts, + variants: parts.each_index.map { |i| { name: i.to_s, config: "{\"sbc.config\":\"test config #{i}\"}" } }, + trafficSeedHi: RULE_TRAFFIC_SEED_HI, trafficSeedLo: RULE_TRAFFIC_SEED_LO, trafficSplit: [0.0, 1.0], fullOnVariant: 0, + applications: [{ name: "website" }], audienceStrict: false, audience: nil, + randomizationType: "switchback", switchbackStartAt: ANCHOR, switchbackPeriodMs: HOUR, + switchbackDesignType: "balanced_block" + } + end + + def unit_experiment(name, id, unit_type) + switchback_experiment(name, id, unit_type, "50/50").merge( + randomizationType: nil, switchbackStartAt: nil, switchbackPeriodMs: nil, switchbackDesignType: nil, + variants: [{ name: "0", config: nil }, { name: "1", config: nil }] + ) + end + + # switchbackClusters in declared (unit type id ascending) order: session_id before user_id. + def clusters + return nil if links.empty? + + [SESSION, USER, "device_id"].each_with_object({}) do |type, map| + links.each { |link| map[link[0]] = link[1] if link[0] == type } + end + end + + def experiment + switchback_experiment("sbc", 900, USER, "34/33/33").merge(switchbackClusters: clusters).merge(extra) + end + + def scheduled(key) + draw(key, PERIOD, RULE_SEED_HI, RULE_SEED_LO, 3) + end + + def create_context(attributes, experiments, units) + @logger = SwitchbackSpecSupport::Logger.new + context = build_context(data_of(experiments), units: units, logger: @logger) + context.set_attributes(attributes) unless attributes.nil? + context + end + + Assigned = Struct.new(:unit, :eligible, :variant, :full_on, :rule_override, :silent, :config, :exposures) + + def sbc(attributes, units) + sbc_with(attributes, [experiment], units) + end + + # Every other experiment resolves (and exposes) first; only "sbc" exposures are returned. + def sbc_with(attributes, experiments, units) + context = create_context(attributes, experiments, units) + experiments.each { |other| context.treatment(other[:name]) unless other[:name] == "sbc" } + variant = context.treatment("sbc") + resolution = context.send(:switchback_resolution_for_test, "sbc") + expect(resolution).not_to be_nil + config = context.variable_value(:"sbc.config", nil) + exposures = @logger.exposures.select { |e| e.name == "sbc" } + # Keyed on the serving status: a strict mismatch is not assigned yet is still listed. + if resolution.serving.status == Absmartly::Switchback::Serving::ABSENT + expect(variant).to eq(0) + expect(config).to be_nil + expect(exposures).to be_empty + return nil + end + Assigned.new(resolution.unit_type, resolution.eligible, variant, resolution.full_on, resolution.rule_override, + resolution.switchback_silent, config, exposures) + end + + # An ineligible cluster is still an assignment, as control, under the first linked unit in + # declared order, with no exposure. + def expect_ineligible(attributes, expected_unit, units) + assignment = sbc(attributes, units) + expect(assignment).not_to be_nil, attributes.inspect + expect([assignment.unit, assignment.eligible, assignment.silent, assignment.variant, assignment.full_on, + assignment.rule_override, assignment.config]).to eq([expected_unit, false, true, 0, false, false, + "test config 0"]) + expect(assignment.exposures).to be_empty, attributes.inspect + end + + def store(value) + { "store" => value } + end + + it "returns only a legacy ineligible control for a missing or unreadable cluster configuration" do + ["null-cluster", "missing-links", "unreadable-path", "geo.city", "'geo.city'", "\"geo.city\"", + "unknown-unit"].each do |broken| + links.clear + case broken + when "unreadable-path" then links << [SESSION, "'geo"] + when "unknown-unit" + # A readable map whose only linked type (device_id) is absent from the context. + links << ["device_id", "session_store"] + expect(sbc({ "session_store" => "s-1" }, { SESSION => "x1", USER => "u1" })).to be_nil + next + when "null-cluster" then nil + when "missing-links" then extra[:switchbackClusters] = {} + else links << [SESSION, broken] + end + attributes = { "geo" => { "city" => "Porto" }, "geo.city" => "Faro", "session_store" => "s-1" } + # The declared unit (user_id) only identifies an ineligible control. + expect_ineligible(attributes, USER, { SESSION => "x1", USER => "u1" }) + expect(sbc(attributes, { SESSION => "x1" })).to be_nil, broken + extra.clear + end + end + + it "uses the serving uid for traffic, not the experiment's unit" do + extra[:trafficSplit] = [0.6, 0.4] + ordinary = unit_experiment("ordinary", 901, USER) + witnesses = [] + (0...1000).each do |i| + uid = "traffic-#{i}" + slot = VariantAssigner.new(uid).assign([0.6, 0.4], RULE_TRAFFIC_SEED_HI, RULE_TRAFFIC_SEED_LO).zero? ? 0 : 1 + witnesses[slot] ||= uid + break if witnesses.compact.length == 2 + end + expect(witnesses.compact.length).to eq(2) + key = "s-18" + expect(scheduled(key)).not_to eq(0) + [false, true].each do |serving_eligible| + assignment = sbc_with({ "session_store" => key, "profile" => store(key) }, [experiment, ordinary], + { SESSION => witnesses[serving_eligible ? 1 : 0], + USER => witnesses[serving_eligible ? 0 : 1] }) + expect(assignment.unit).to eq(SESSION) + expect(assignment.eligible).to eq(serving_eligible) + expect(assignment.variant).to eq(serving_eligible ? scheduled(key) : 0) + # A traffic miss on an eligible cluster is still recorded, under the serving unit. + expect(assignment.exposures.map { |e| [e.unit, e.eligible] }).to eq([[SESSION, serving_eligible]]) + end + end + + it "serves the value of one matching unit" do + assignment = sbc({ "profile" => store("s-17") }, { USER => "u1" }) + expect([assignment.eligible, assignment.unit, assignment.variant]).to eq([true, USER, scheduled("s-17")]) + end + + it "lists a strict audience mismatch on an eligible cluster as control and records it" do + extra.merge!(audience: STRICT_GOLD_AUDIENCE, audienceStrict: true) + assignment = sbc({ "session_store" => "s-17" }, { SESSION => "x1" }) + expect([assignment.unit, assignment.eligible, assignment.silent, assignment.variant]) + .to eq([SESSION, true, false, 0]) + expect(assignment.exposures.map { |e| [e.audience_mismatch, e.assigned] }).to eq([[true, false]]) + end + + it "serves the value two agreeing units give" do + assignment = sbc({ "profile" => store("s-17"), "session_store" => "s-17" }, { USER => "u1", SESSION => "x1" }) + expect([assignment.eligible, assignment.variant]).to eq([true, scheduled("s-17")]) + end + + it "makes two disagreeing units ineligible" do + # session_id is first in declared order whatever the unit order. + expect_ineligible({ "profile" => store("s-17"), "session_store" => "s-18" }, SESSION, + { USER => "u1", SESSION => "x1" }) + end + + # A context holds one uid per unit type, so only the single-unit path is reproducible. + it "serves one unit of a type with one path" do + key = "s-17" + expect(scheduled(key)).not_to eq(0) + context = create_context({ "session_store" => key }, [experiment], { SESSION => "x1" }) + expect { context.set_unit(SESSION, "x2") }.to raise_error(IllegalStateException) + + assignment = sbc({ "session_store" => key }, { SESSION => "x1" }) + expect([assignment.eligible, assignment.variant]).to eq([true, scheduled(key)]) + end + + it "does not apply without a matching unit" do + expect(sbc({ "session_store" => "s-1" }, { "device_id" => "d1" })).to be_nil + expect(sbc({ "session_store" => "s-1" }, {})).to be_nil + end + + it "makes a matching unit without a value ineligible" do + expect_ineligible({ "other" => "s-1" }, USER, { USER => "u1" }) + expect_ineligible({ "other" => "s-1" }, SESSION, { USER => "u1", SESSION => "x1" }) + end + + it "makes values that are neither strings nor integers ineligible" do + [1.5, 3.0, true, { "a" => 1 }, ["a"], ""].each do |value| + expect_ineligible({ "session_store" => value }, SESSION, { SESSION => "x1" }) + end + end + + it "keys whole numbers by their decimal text" do + expect(scheduled("17")).not_to eq(0) + assignment = sbc({ "session_store" => 17 }, { SESSION => "x1" }) + expect([assignment.eligible, assignment.variant]).to eq([true, scheduled("17")]) + # Equal to the string "17" from another unit type, so the two agree. + expect(sbc({ "session_store" => 17, "profile" => store("17") }, { SESSION => "x1", USER => "u1" }).eligible) + .to be(true) + end + + it "reads nested and array paths" do + links.replace([[SESSION, "items/1/store"]]) + assignment = sbc({ "items" => [store("a"), store("b")] }, { SESSION => "x1" }) + expect(assignment.variant).to eq(scheduled("b")) + expect(scheduled("a")).not_to eq(scheduled("b")) + end + + it "exposes the first matching unit in declared order whatever the unit order" do + key = "s-18" + expect(scheduled(key)).not_to eq(0) + assignment = sbc({ "profile" => store(key), "session_store" => key }, { USER => "u1", SESSION => "x1" }) + expect([assignment.unit, assignment.exposures[0].unit, assignment.variant]).to eq([SESSION, SESSION, scheduled(key)]) + end + + it "never publishes an exposure for an ineligible cluster" do + published = SwitchbackSpecSupport::Publisher.new + @logger = SwitchbackSpecSupport::Logger.new + context = build_context(data_of([experiment]), units: { USER => "u1", SESSION => "x1" }, + publisher: published, logger: @logger) + context.set_attributes({ "session_store" => "a", "profile" => store("b") }) + expect(context.treatment("sbc")).to eq(0) + expect(context.pending_count).to eq(0) + context.publish + expect(published.events).to be_empty + expect(@logger.exposures).to be_empty + end + + it "does not serve a unit without a value even if it is first in declared order" do + key = "s-17" + expect(scheduled(key)).not_to eq(0) + assignment = sbc({ "profile" => store(key) }, { SESSION => "x1", USER => "u1" }) + expect([assignment.unit, assignment.exposures[0].unit, assignment.variant]).to eq([USER, USER, scheduled(key)]) + end + + it "makes a value outside the allow-list ineligible" do + extra[:switchbackClusterValues] = %w[s-1 s-2] + expect_ineligible({ "session_store" => "s-3" }, SESSION, { SESSION => "x1" }) + allowed = sbc({ "session_store" => "s-2" }, { SESSION => "x1" }) + expect([allowed.eligible, allowed.variant]).to eq([true, scheduled("s-2")]) + end + + it "assigns every value with a null allow-list" do + extra[:switchbackClusterValues] = nil + 20.times do |i| + assignment = sbc({ "session_store" => "s-#{i}" }, { SESSION => "x1" }) + expect([assignment.eligible, assignment.variant]).to eq([true, scheduled("s-#{i}")]) + end + end + + it "does not fall back to the experiment's unit without a linked unit" do + links.replace([[SESSION, "session_store"]]) + key = "s-17" + expect(scheduled(key)).not_to eq(0) + expect(sbc({ "session_store" => key, "profile" => store(key) }, { USER => "u1" })).to be_nil + linked = sbc({ "session_store" => key }, { USER => "u1", SESSION => "x1" }) + expect([linked.unit, linked.variant]).to eq([SESSION, scheduled(key)]) + end + + # The Collector's wire-rule oracle SdkSwitchbackRule, transcribed: period from the anchor + # re-ceiled to the hour, traffic on the serving uid's hash, then the draw over the key. + module SdkSwitchbackRule + def self.period_index(experiment, now) + start_at = experiment[:switchbackStartAt] + period_ms = experiment[:switchbackPeriodMs] + return nil if start_at.nil? || period_ms.nil? || period_ms <= 0 || experiment[:split].length < 2 + + anchor = -((-start_at).div(HOUR)) * HOUR + now < anchor ? nil : (now - anchor).div(period_ms) + end + + # [variant, eligible] + def self.evaluate(experiment, uid, cluster_key, now) + period = period_index(experiment, now) + return [0, false] if cluster_key.nil? || period.nil? + + eligible = VariantAssigner.new(uid).assign(experiment[:trafficSplit], experiment[:trafficSeedHi], + experiment[:trafficSeedLo]) == 1 + return [0, false] unless eligible + + seed = (experiment[:seedHi] << 32) | (experiment[:seedLo] & 0xffffffff) + [Absmartly::Switchback::Assigner.assign(cluster_key, period, seed, experiment[:split].length), true] + end + end + + def grid_context(cluster, uid, key) + links.replace([[SESSION, "session_store"]]) + extra[:switchbackClusterValues] = nil + case cluster + when :disagreeing_second_source + links << [USER, "profile/store"] + create_context({ "session_store" => key, "profile" => store("#{key}-other") }, [experiment], + { SESSION => uid, USER => "u-#{uid}" }) + when :missing_value then create_context({ "other" => key }, [experiment], { SESSION => uid }) + when :filtered_value + extra[:switchbackClusterValues] = ["#{key}-allowed"] + create_context({ "session_store" => key }, [experiment], { SESSION => uid }) + else create_context({ "session_store" => key }, [experiment], { SESSION => uid }) + end + end + + it "matches the SdkSwitchbackRule wire-rule parity grid" do + counts = Hash.new(0) + %i[single disagreeing_second_source missing_value filtered_value].each do |cluster| + [ANCHOR, ANCHOR + 7 * HOUR].each do |anchor| + [HOUR, 2 * HOUR, 24 * HOUR].each do |period_ms| + 6.times do |u| + uid = "uid-#{u}" + ["s-1", "s-2", "42", "Lisboa"].each do |key| + [anchor - HOUR, anchor - 1, anchor, anchor + period_ms - 1, anchor + period_ms, + anchor + 3 * period_ms + 5, anchor + 11 * period_ms].each do |now| + extra.merge!(trafficSplit: [0.3, 0.7], switchbackStartAt: anchor, switchbackPeriodMs: period_ms) + clock.now = now + oracle_key = cluster == :single ? key : nil + context = grid_context(cluster, uid, key) + oracle = SdkSwitchbackRule.evaluate(experiment, uid, oracle_key, now) + message = [cluster, anchor, period_ms, uid, key, now].join("/") + expect(context.treatment("sbc")).to eq(oracle[0]), message + expect(context.send(:switchback_resolution_for_test, "sbc").eligible).to eq(oracle[1]), message + # Before the anchor nothing is recorded; from it a keyed cluster records one + # exposure whose eligibility is the oracle's (a traffic miss included). + recorded = !oracle_key.nil? && now >= anchor + expect(@logger.exposures.length).to eq(recorded ? 1 : 0), message + expect(@logger.exposures[0].eligible).to eq(oracle[1]), message if recorded + next unless cluster == :single + + counts[oracle[1]] += 1 + counts[:traffic_miss] += 1 if !oracle[1] && now >= anchor + end + end + end + end + end + end + expect(counts[true]).to be > 100 + expect(counts[false]).to be > 100 + expect(counts[:traffic_miss]).to be > 0 + + # The deliberate divergence: an anchor off the hour is unservable, while the transcribed + # oracle would re-ceil it and draw. + unaligned = ANCHOR + 7 * HOUR + 1 + extra.merge!(trafficSplit: [0.0, 1.0], switchbackStartAt: unaligned, switchbackPeriodMs: HOUR) + clock.now = ANCHOR + 8 * HOUR + 5 + expect(SdkSwitchbackRule.period_index(experiment, clock.now)).not_to be_nil + expect(SdkSwitchbackRule.evaluate(experiment, "uid-0", "s-1", clock.now)[1]).to be(true) + context = grid_context(:single, "uid-0", "s-1") + expect(context.treatment("sbc")).to eq(0) + expect(context.send(:switchback_resolution_for_test, "sbc").eligible).to be(false) + expect(@logger.exposures).to be_empty + end + end +end diff --git a/spec/context_switchback_spec.rb b/spec/context_switchback_spec.rb new file mode 100644 index 00000000..7f17a1f1 --- /dev/null +++ b/spec/context_switchback_spec.rb @@ -0,0 +1,1436 @@ +# frozen_string_literal: true + +require "switchback_support" + +# Port of java-sdk ContextSwitchbackTest (core-api/src/test/java/com/absmartly/sdk/ContextSwitchbackTest.java). +module ContextSwitchbackSpec + RSpec.describe "Context switchbacks" do + include SwitchbackSpecSupport + + UNIT_TYPE = "store_id" + UID = "e791e240fcd3df7d238cfc285f475e8152fcc0ec" + # Hashing.hash_unit(UID): the MD5/base64url string the Collector also produces. + UID_HASH = "pAE3a1i5Drs5mKRNq56adA" + HOUR = SwitchbackSpecSupport::HOUR + DAY = SwitchbackSpecSupport::DAY + ANCHOR = SwitchbackSpecSupport::ANCHOR + SEED_HI = -5 + SEED_LO = -7 + CLUSTER_PATH = "store_key" + CLUSTER_KEY = "store-42" + # Periods 0..11 of the raw key "store-42" under seed (SEED_HI, SEED_LO), from java-sdk's + # independent Python reference. + EXPECTED_2_ARMS = [0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1].freeze + EXPECTED_3_ARMS = [0, 2, 1, 2, 1, 0, 1, 2, 0, 1, 0, 2].freeze + EXPECTED_10_ARMS = [8, 3, 7, 4, 2, 0, 5, 1, 9, 6, 3, 7].freeze + # The same reference fed UID_HASH and the raw UID: what keying by the unit would serve. + UID_HASH_3_ARMS = [1, 2, 0, 2, 1, 0, 2, 0, 1, 1, 2, 0].freeze + UID_3_ARMS = [2, 0, 1, 0, 1, 2, 1, 2, 0, 0, 1, 2].freeze + ASSIGN_VARIANT_1 = '{"rules":[{"type":"assign","environments":[],"variant":1}]}' + ASSIGN_VARIANT_2 = '{"rules":[{"type":"assign","environments":[],"variant":2}]}' + # An audience the default context never matches (no "tier" attribute). + STRICT_GOLD_AUDIENCE = '{"filter":[{"eq":[{"var":"tier"},{"value":"gold"}]}]}' + + let(:clock) { SwitchbackSpecSupport::MutableClock.new(ANCHOR) } + let(:provider) { double("ContextDataProvider") } + + def switchback(id = 1, name = "exp_sb", arms = 2, period_ms = HOUR, **extra) + { + id: id, name: name, unitType: UNIT_TYPE, iteration: 1, seedHi: SEED_HI, seedLo: SEED_LO, + split: Array.new(arms) { 1.0 / arms }, + variants: Array.new(arms) { |i| { name: ("A".ord + i).chr, config: "{\"sb.arm\":#{i}}" } }, + trafficSeedHi: 1, trafficSeedLo: 2, trafficSplit: [0.0, 1.0], fullOnVariant: 0, + applications: [{ name: "website" }], audienceStrict: false, audience: nil, + randomizationType: "switchback", switchbackClusters: { UNIT_TYPE => CLUSTER_PATH }, + switchbackStartAt: ANCHOR, switchbackPeriodMs: period_ms, switchbackCarryoverDurationMs: 0, + switchbackBurnInDurationMs: 0, switchbackBurnOutDurationMs: 0, switchbackDesignType: "balanced_block", + switchbackEstimand: "global_average_treatment_effect" + }.merge(extra) + end + + def unit_twin(experiment) + experiment.merge(randomizationType: nil, switchbackClusters: nil, switchbackStartAt: nil, + switchbackPeriodMs: nil) + end + + def create_context(experiments, units: { UNIT_TYPE => UID }, holdouts: nil, **options) + build_context(data_of(experiments, holdouts), units: units, attributes: { CLUSTER_PATH => CLUSTER_KEY }, + provider: provider, **options) + end + + def refresh_to(context, experiments, holdouts = nil) + allow(provider).to receive(:context_data).and_return(ready(data_of(experiments, holdouts))) + context.refresh + end + + def sb_exposure(id, name, variant, exposed_at, assigned, eligible) + exposure(id, name, UNIT_TYPE, variant, exposed_at, assigned, eligible) + end + + def rule_exposure(name, variant, exposed_at) + exposure(1, name, UNIT_TYPE, variant, exposed_at, false, true, false, false, false, false, true) + end + + def strict_mismatch_exposure(exposed_at) + exposure(1, "exp_sb", UNIT_TYPE, 0, exposed_at, false, true, false, false, false, true, false) + end + + def peek_schedule(context, name, period_ms, periods) + Array.new(periods) do |i| + clock.now = ANCHOR + i * period_ms + context.peek_treatment(name) + end + end + + def seed + (SEED_HI << 32) | (SEED_LO & 0xffffffff) + end + + def serialized_publish(context) + publisher = context.send(:event_handler) + context.publish + DefaultContextEventSerializer.new.serialize(publisher.events.last) + end + + it "keys the cluster by the raw cluster value, neither hashed nor the unit uid" do + expect(Hashing.hash_unit(UID)).to eq(UID_HASH) + + context = create_context([switchback(1, "exp_sb", 3)]) + served = peek_schedule(context, "exp_sb", HOUR, 12) + + expect(served).to eq(EXPECTED_3_ARMS) + expect(served).not_to eq(UID_HASH_3_ARMS) + expect(served).not_to eq(UID_3_ARMS) + hashed = Hashing.hash_unit(CLUSTER_KEY) + expect(served).to eq((0...12).map { |i| Absmartly::Switchback::Assigner.assign(CLUSTER_KEY, i, seed, 3) }) + expect((0...12).map { |i| Absmartly::Switchback::Assigner.assign(hashed, i, seed, 3) }).not_to eq(served) + end + + it "serves two, three and ten arm permutations" do + context = create_context([switchback(1, "exp_2", 2), switchback(2, "exp_3", 3), switchback(3, "exp_10", 10)]) + + expect(peek_schedule(context, "exp_2", HOUR, 12)).to eq(EXPECTED_2_ARMS) + expect(peek_schedule(context, "exp_3", HOUR, 12)).to eq(EXPECTED_3_ARMS) + expect(peek_schedule(context, "exp_10", HOUR, 12)).to eq(EXPECTED_10_ARMS) + end + + it "changes period at the exact one-hour edge milliseconds" do + context = create_context([switchback]) + [[ANCHOR - 1, 0], [ANCHOR, EXPECTED_2_ARMS[0]], [ANCHOR + HOUR - 1, EXPECTED_2_ARMS[0]], + [ANCHOR + HOUR, EXPECTED_2_ARMS[1]], [ANCHOR + 3 * HOUR - 1, EXPECTED_2_ARMS[2]], + [ANCHOR + 3 * HOUR, EXPECTED_2_ARMS[3]]].each do |now, expected| + clock.now = now + expect(context.peek_treatment("exp_sb")).to eq(expected), now.to_s + end + end + + it "changes period at the exact 24-hour edge milliseconds" do + context = create_context([switchback(1, "exp_sb", 2, DAY)]) + [[ANCHOR - 1, 0], [ANCHOR, EXPECTED_2_ARMS[0]], [ANCHOR + HOUR, EXPECTED_2_ARMS[0]], + [ANCHOR + DAY - 1, EXPECTED_2_ARMS[0]], [ANCHOR + DAY, EXPECTED_2_ARMS[1]], + [ANCHOR + 4 * DAY - 1, EXPECTED_2_ARMS[3]], [ANCHOR + 4 * DAY, EXPECTED_2_ARMS[4]]].each do |now, expected| + clock.now = now + expect(context.peek_treatment("exp_sb")).to eq(expected), now.to_s + end + end + + # The anchor is used as served, never rounded; before it the experiment is a silent + # control. An anchor that is not hour aligned is unservable in every period. + it "treats an unaligned start as unservable and pre-anchor as ineligible" do + start = ANCHOR + 1_234_567 + context = create_context([switchback(1, "exp_aligned", 2, HOUR, switchbackStartAt: ANCHOR + HOUR), + switchback(2, "exp_unaligned", 2, HOUR, switchbackStartAt: start)]) + + [ANCHOR, start - 1, start, ANCHOR + HOUR - 1].each do |now| + clock.now = now + expect(context.treatment("exp_aligned")).to eq(0) + expect(context.treatment("exp_unaligned")).to eq(0) + end + expect(context.pending_count).to eq(0) + (1...4).each do |i| + clock.now = ANCHOR + i * HOUR + expect(context.treatment("exp_aligned")).to eq(EXPECTED_2_ARMS[i - 1]) + expect(context.treatment("exp_unaligned")).to eq(0) + clock.now = start + i * HOUR + expect(context.treatment("exp_unaligned")).to eq(0) + end + + expect(published_exposures(context)).to eq([ + sb_exposure(1, "exp_aligned", EXPECTED_2_ARMS[0], ANCHOR + HOUR, true, true), + sb_exposure(1, "exp_aligned", EXPECTED_2_ARMS[1], ANCHOR + 2 * HOUR, true, true), + sb_exposure(1, "exp_aligned", EXPECTED_2_ARMS[2], ANCHOR + 3 * HOUR, true, true) + ]) + end + + # The Collector Registry's anchor bounds: hour aligned and in [0, 10000-01-01T00:00:00Z). + it "treats an anchor off the hour or out of range as unservable" do + max_anchor = 253_402_300_800_000 + long_max = (2**63) - 1 + [ANCHOR + 1, ANCHOR - 1, ANCHOR + 30 * 60_000, ANCHOR + HOUR - 1, -HOUR, -1, max_anchor, + max_anchor + HOUR, long_max - (long_max % HOUR), nil, "1767225600000", ANCHOR.to_f].each do |start_at| + clock.now = 0 + context = create_context([switchback(switchbackStartAt: start_at)]) + [0, ANCHOR, ANCHOR + 2 * HOUR + 1, start_at.is_a?(Integer) ? start_at : ANCHOR, + (start_at.is_a?(Integer) ? start_at : ANCHOR) + HOUR, max_anchor + DAY].each do |now| + clock.now = now + expect(context.treatment("exp_sb")).to eq(0), "start_at #{start_at.inspect} now #{now}" + expect(context.variable_value("sb.arm", -1)).to eq(0) + end + expect(context.pending_count).to eq(0), "start_at #{start_at.inspect}" + expect(published_exposures(context)).to eq([]) + end + + # In-range hour-aligned anchors, 0 and the last hour before the bound included, serve. + [0, ANCHOR, max_anchor - HOUR].each do |start_at| + clock.now = start_at + HOUR + context = create_context([switchback(switchbackStartAt: start_at)]) + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[1]), start_at.to_s + expect(context.pending_count).to eq(1) + end + end + + # The period index is exact 64-bit integer arithmetic, far beyond 2**53. + it "draws an exact period index in the far future" do + long_max = (2**63) - 1 + context = create_context([switchback(1, "exp_sb", 3, 1)]) + [2**53 + 1, 2**62 + 3, long_max].each do |now| + clock.now = now + expect(context.peek_treatment("exp_sb")) + .to eq(Absmartly::Switchback::Assigner.assign(CLUSTER_KEY, now - ANCHOR, seed, 3)), now.to_s + end + end + + it "never falls back to unit assignment with a null start" do + context = create_context([switchback(switchbackStartAt: nil)]) + 4.times do |i| + clock.now = ANCHOR + i * HOUR + expect(context.treatment("exp_sb")).to eq(0) + # Variant 0's own config, like any ineligible assignment. + expect(context.variable_value("sb.arm", -1)).to eq(0) + end + expect(context.pending_count).to eq(0) + end + + it "caches the period and rolls over to the next with one exposure each" do + context = create_context([switchback]) + + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(context.pending_count).to eq(1) + clock.now = ANCHOR + HOUR - 1 + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(context.peek_treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(context.pending_count).to eq(1) + + clock.now = ANCHOR + HOUR + expect(context.peek_treatment("exp_sb")).to eq(EXPECTED_2_ARMS[1]) + expect(context.pending_count).to eq(1) + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[1]) + expect(context.pending_count).to eq(2) + clock.now = ANCHOR + HOUR + 30 * 60_000 + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[1]) + expect(context.pending_count).to eq(2) + + expect(published_exposures(context)).to eq([ + sb_exposure(1, "exp_sb", EXPECTED_2_ARMS[0], ANCHOR + 10, true, true), + sb_exposure(1, "exp_sb", EXPECTED_2_ARMS[1], ANCHOR + HOUR, true, true) + ]) + end + + it "follows the period on variable lookups and exposes once per period" do + context = create_context([switchback(1, "exp_sb", 3)]) + + expect(context.variable_keys_list).to eq({ "sb.arm": ["exp_sb"] }) + expect(context.experiments).to eq(["exp_sb"]) + 3.times do |i| + clock.now = ANCHOR + i * HOUR + expect(context.peek_variable_value("sb.arm", -1)).to eq(EXPECTED_3_ARMS[i]) + expect(context.variable_value("sb.arm", -1)).to eq(EXPECTED_3_ARMS[i]) + expect(context.variable_value("sb.arm", -1)).to eq(EXPECTED_3_ARMS[i]) + expect(context.treatment("exp_sb")).to eq(EXPECTED_3_ARMS[i]) + end + expect(context.pending_count).to eq(3) + end + + it "leaves a missing cluster unit unassigned without a fallback" do + context = create_context([switchback(unitType: "user_id")], units: { "user_id" => UID }) + + 3.times do |i| + clock.now = ANCHOR + i * HOUR + expect(context.peek_treatment("exp_sb")).to eq(0) + expect(context.treatment("exp_sb")).to eq(0) + expect(context.variable_value("sb.arm", -1)).to eq(-1) + end + expect(context.pending_count).to eq(0) + + context.set_unit(UNIT_TYPE, UID) + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[2]) + expect(published_exposures(context)).to eq([sb_exposure(1, "exp_sb", EXPECTED_2_ARMS[2], ANCHOR + 2 * HOUR, + true, true)]) + end + + it "serves the full-on variant in every period" do + context = create_context([switchback(1, "exp_sb", 3, HOUR, fullOnVariant: 2)]) + 4.times do |i| + clock.now = ANCHOR + i * HOUR + expect(context.treatment("exp_sb")).to eq(2) + end + exposures = published_exposures(context) + expect(exposures.length).to eq(4) + expect(exposures.map { |e| [e.variant, e.full_on] }.uniq).to eq([[2, true]]) + end + + it "lets an override and a custom assignment win in every period" do + context = create_context([switchback(1, "exp_override", 3), switchback(2, "exp_custom", 3)]) + context.set_override("exp_override", 7) + context.set_custom_assignment("exp_custom", 2) + + 3.times do |i| + clock.now = ANCHOR + i * HOUR + expect(context.treatment("exp_override")).to eq(7) + expect(context.treatment("exp_custom")).to eq(2) + end + exposures = published_exposures(context) + expect(exposures.length).to eq(6) + exposures.each do |e| + expect(e.name == "exp_override" ? [e.overridden, e.variant] : [e.custom, e.variant]) + .to eq(e.name == "exp_override" ? [true, 7] : [true, 2]) + end + end + + # Traffic uses the serving unit's traffic hash: it matches a unit twin with the same traffic + # seed and stays fixed across periods. + it "keeps traffic eligibility sticky per serving unit" do + counts = Hash.new(0) + 24.times do |u| + clock.now = ANCHOR + sb = switchback(1, "exp_sb", 2, HOUR, trafficSplit: [0.5, 0.5]) + twin = switchback(2, "exp_unit", 2, HOUR, trafficSplit: [0.5, 0.5], randomizationType: nil, + switchbackStartAt: nil) + context = create_context([sb, twin], units: { UNIT_TYPE => "store_#{u}" }) + context.treatment("exp_unit") + 4.times do |i| + clock.now = ANCHOR + i * HOUR + context.treatment("exp_sb") + end + + exposures = published_exposures(context) + expect(exposures.length).to eq(5) + twin_eligible = exposures[0].eligible + exposures[1..].each do |e| + expect(e.name).to eq("exp_sb") + expect(e.eligible).to eq(twin_eligible) + expect(e.variant).to eq(0) unless twin_eligible + end + counts[twin_eligible] += 1 + end + expect(counts[true]).to be > 0 + expect(counts[false]).to be > 0 + end + + it "leaves unit experiments unaffected" do + context = create_context([switchback(randomizationType: "unit"), + switchback(2, "exp_absent", 2, HOUR, randomizationType: nil)]) + variant = context.treatment("exp_sb") + absent = context.treatment("exp_absent") + (1...6).each do |i| + clock.now = ANCHOR + i * HOUR + expect(context.treatment("exp_sb")).to eq(variant) + expect(context.treatment("exp_absent")).to eq(absent) + end + expect(context.pending_count).to eq(2) + end + + it "re-resolves when grid fields change on refresh, but not for analysis-only fields" do + context = create_context([switchback]) + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(context.pending_count).to eq(1) + + refresh_to(context, [switchback(switchbackBurnInDurationMs: 600_000, switchbackBurnOutDurationMs: 300_000, + switchbackCarryoverDurationMs: 900_000, switchbackEstimand: "other")]) + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(context.pending_count).to eq(1) + + # Period index 0 under both grids, so only the config comparison can invalidate. + refresh_to(context, [switchback(1, "exp_sb", 2, 2 * HOUR)]) + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(context.pending_count).to eq(2) + + refresh_to(context, [switchback(1, "exp_sb", 2, 2 * HOUR, switchbackDesignType: "other_design")]) + context.treatment("exp_sb") + expect(context.pending_count).to eq(3) + + refresh_to(context, [switchback(1, "exp_sb", 2, 2 * HOUR, randomizationType: "unit")]) + context.treatment("exp_sb") + expect(context.pending_count).to eq(4) + + refresh_to(context, [switchback(1, "exp_sb", 2, 2 * HOUR)]) + context.treatment("exp_sb") + expect(context.pending_count).to eq(5) + + # The cluster map (types, paths and their order) and the allow-list are identity. + refresh_to(context, [switchback(1, "exp_sb", 2, 2 * HOUR, switchbackClusters: { UNIT_TYPE => "'store_key'" })]) + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(context.pending_count).to eq(6) + + link_added = { UNIT_TYPE => "'store_key'", "device_id" => "city" } + refresh_to(context, [switchback(1, "exp_sb", 2, 2 * HOUR, switchbackClusters: link_added)]) + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(context.pending_count).to eq(7) + + reordered = { "device_id" => "city", UNIT_TYPE => "'store_key'" } + refresh_to(context, [switchback(1, "exp_sb", 2, 2 * HOUR, switchbackClusters: reordered)]) + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(context.pending_count).to eq(8) + + refresh_to(context, [switchback(1, "exp_sb", 2, 2 * HOUR, switchbackClusters: reordered, + switchbackClusterValues: [CLUSTER_KEY])]) + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(context.pending_count).to eq(9) + + # An unrelated unitType edit is not identity: switchbacks never read it. + refresh_to(context, [switchback(1, "exp_sb", 2, 2 * HOUR, switchbackClusters: reordered, + switchbackClusterValues: [CLUSTER_KEY], + unitType: "anything")]) + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(context.pending_count).to eq(9) + end + + it "re-reads the cluster key when the iteration changes" do + context = create_context([switchback(1, "exp_sb", 3, HOUR, switchbackClusters: { UNIT_TYPE => "city" })]) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + expect(context.treatment("exp_sb")).to eq(draw("Lisboa", 0, SEED_HI, SEED_LO, 3)) + context.set_attribute("city", "Faro") + expect(context.treatment("exp_sb")).to eq(draw("Lisboa", 0, SEED_HI, SEED_LO, 3)) + + clock.now = ANCHOR + 20 + refresh_to(context, [switchback(1, "exp_sb", 3, HOUR, switchbackClusters: { UNIT_TYPE => "city" }, iteration: 2)]) + expect(context.treatment("exp_sb")).to eq(draw("Faro", 0, SEED_HI, SEED_LO, 3)) + expect(draw("Faro", 0, SEED_HI, SEED_LO, 3)).not_to eq(draw("Lisboa", 0, SEED_HI, SEED_LO, 3)) + expect(context.pending_count).to eq(2) + end + + # A call that started before a refresh installed the first switchback (so it read no clock) + # exposes with the reading that chose its period, not a later one across a boundary. + %i[treatment variable_value peek_treatment].each do |api| + it "stamps #{api} racing the first switchback's install with its period's reading" do + # A unit experiment declares the key, so the variable read reaches the lock too; after the + # refresh it is a switchback. + context = create_context([unit_twin(switchback)]) + context.peek_treatment("exp_sb") + lock = context.instance_variable_get(:@assignment_mutex) + worker = nil + lock.synchronize do + worker = Thread.new do + value = case api + when :treatment then context.treatment("exp_sb") + when :peek_treatment then context.peek_treatment("exp_sb") + else context.variable_value("sb.arm", -1) + end + # Nothing of this call's reading stays on the thread. + [value, Thread.current.keys.grep(/absmartly/).map { |k| Thread.current[k] }.compact] + end + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5 + Thread.pass until worker.status == "sleep" || !worker.alive? || + Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline + expect(worker.status).to eq("sleep") + refresh_to(context, [switchback]) + clock.now = ANCHOR + HOUR + clock.next_read = ANCHOR + HOUR - 1 + end + expect(worker.value).to eq([EXPECTED_2_ARMS[0], []]) + expect(EXPECTED_2_ARMS[0]).not_to eq(EXPECTED_2_ARMS[1]) + expected = api == :peek_treatment ? [] : [sb_exposure(1, "exp_sb", EXPECTED_2_ARMS[0], ANCHOR + HOUR - 1, true, true)] + expect(published_exposures(context)).to eq(expected) + end + end + + # A resolution that raises after taking the fallback reading leaves no state behind on the thread, + # so the thread's next read (another context racing its own first switchback) uses its own reading. + it "keeps a raising resolution's fallback reading out of later calls" do + raising = Class.new(AudienceMatcher) do + def evaluate(*) + raise "matcher failed" + end + end.new(DefaultAudienceDeserializer.new) + audience = '{"filter":[{"value":true}]}' + first = create_context([unit_twin(switchback(audience: audience))], audience_matcher: raising) + second = create_context([unit_twin(switchback)]) + second.peek_treatment("exp_sb") + + # The same worker raises on first, then makes its own first read of second, which this thread + # holds back until a refresh installs second's switchback. + # It is started while this thread holds first's lock, so it can only reach the lock once + # the refresh below has installed first's switchback. + go = Queue.new + worker = nil + blocked_in = lambda do |method| + in_method = lambda do + worker.status == "sleep" && worker.backtrace.to_a.any? { |l| l.include?("`#{method}'") || l.include?("##{method}'") } + end + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5 + Thread.pass until in_method.call || !worker.alive? || Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline + expect(in_method.call).to be(true), "worker is not blocked in #{method}" + end + first.instance_variable_get(:@assignment_mutex).synchronize do + worker = Thread.new do + error = begin + first.peek_treatment("exp_sb") + nil + rescue RuntimeError => e + e.message + end + leftovers = Thread.current.keys.grep(/absmartly/).map { |k| Thread.current[k] }.compact + go.pop + [error, leftovers, second.variable_value("sb.arm", -1)] + end + blocked_in.call("peek_treatment") + refresh_to(first, [switchback(audience: audience)]) + clock.now = ANCHOR + HOUR - 1 + end + second.instance_variable_get(:@assignment_mutex).synchronize do + go << true + blocked_in.call("variable_value") + refresh_to(second, [switchback]) + clock.now = ANCHOR + HOUR + end + error, leftovers, value = worker.value + expect(error).to eq("matcher failed") + expect(leftovers).to eq([]) + expect(value).to eq(EXPECTED_2_ARMS[1]) + expect(published_exposures(second).map(&:exposed_at)).to eq([ANCHOR + HOUR]) + end + + # A switchback slot cached before a refresh replaced it with a unit experiment of the same name + # is dropped, even when the new data has no switchback left. + it "drops a switchback's slots when a refresh leaves no switchback" do + clock.now = ANCHOR - 1 + context = create_context([switchback(fullOnVariant: 1)]) + expect(context.treatment("exp_sb")).to eq(1) + expect(context.pending_count).to eq(1) + + refresh_to(context, [unit_twin(switchback(fullOnVariant: 1))]) + expect(context.treatment("exp_sb")).to eq(1) + expect(context.pending_count).to eq(2) + expect(context.instance_variable_get(:@switchback_epochs)).to be_empty + end + + it "starts the grid when a refresh sets the start" do + context = create_context([switchback(switchbackStartAt: nil)]) + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(0) + + refresh_to(context, [switchback]) + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(context.pending_count).to eq(1) + end + + def holdout(split) + { id: 11, name: "holdout_a", unitType: UNIT_TYPE, iteration: 1, seedHi: 13, seedLo: 111, split: split, + trafficSeedHi: 0, trafficSeedLo: 0, trafficSplit: [0.0, 1.0], fullOnVariant: 0, applications: [], + variants: split.each_index.map { |i| { name: i.to_s, config: nil } }, audienceStrict: false, + audience: nil } + end + + # Holdouts never apply: one that would hold the unit out neither suppresses the switchback + # nor records its own exposure through it. + it "never applies a holdout to a switchback" do + # split [0.1, 0.9] gives UID arm 0 (held out) for an ordinary experiment. + context = create_context([switchback(holdoutIds: [11])], holdouts: [holdout([0.1, 0.9])]) + 3.times do |i| + clock.now = ANCHOR + i * HOUR + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[i]) + expect(context.variable_value("sb.arm", -1)).to eq(EXPECTED_2_ARMS[i]) + end + + expect(published_exposures(context)).to eq([ + sb_exposure(1, "exp_sb", EXPECTED_2_ARMS[0], ANCHOR, true, true), + sb_exposure(1, "exp_sb", EXPECTED_2_ARMS[1], ANCHOR + HOUR, true, true), + sb_exposure(1, "exp_sb", EXPECTED_2_ARMS[2], ANCHOR + 2 * HOUR, true, true) + ]) + end + + it "resolves no holdouts for a switchback" do + context = create_context([switchback(holdoutIds: [11]), unit_twin(switchback(2, "exp_unit", holdoutIds: [11]))], + holdouts: [holdout([0.1, 0.9])]) + expect(context.send(:experiment, "exp_sb").holdouts).to be_nil + expect(context.send(:experiment, "exp_unit").holdouts.map(&:id)).to eq([11]) + end + + it "would hold the unit out of the same experiment as a unit experiment" do + context = create_context([unit_twin(switchback(holdoutIds: [11]))], holdouts: [holdout([0.1, 0.9])]) + expect(context.treatment("exp_sb")).to eq(0) + expect(published_exposures(context).map(&:name)).to eq(["holdout_a"]) + end + + # Rules come first, before the anchor too, with ruleOverride set and the exposure recorded. + it "lets an assignment rule override the schedule" do + 10.times do |u| + clock.now = ANCHOR - 1 + context = create_context([switchback(assignmentRules: ASSIGN_VARIANT_1)], units: { UNIT_TYPE => "user-#{u}" }) + expect(context.treatment("exp_sb")).to eq(1) + expect(context.variable_value("sb.arm", -1)).to eq(1) + 4.times do |i| + clock.now = ANCHOR + i * HOUR + expect(context.treatment("exp_sb")).to eq(1) + end + exposures = published_exposures(context) + expect(exposures).to eq([rule_exposure("exp_sb", 1, ANCHOR - 1)] + + (0...4).map { |i| rule_exposure("exp_sb", 1, ANCHOR + i * HOUR) }) + end + end + + # An unservable schedule only replaces the draw: full-on and a matching rule still apply. + it "lets full-on and rules apply on an unservable schedule" do + context = create_context([switchback(1, "sb_full_on", 2, HOUR, switchbackStartAt: nil, fullOnVariant: 1), + switchback(2, "sb_rules", 2, HOUR, switchbackPeriodMs: 0, + assignmentRules: ASSIGN_VARIANT_1), + switchback(3, "sb_unaligned_rules", 2, HOUR, switchbackStartAt: ANCHOR + 1, + assignmentRules: ASSIGN_VARIANT_1)], + units: { UNIT_TYPE => "15" }) + + expect(context.treatment("sb_full_on")).to eq(1) + expect(context.treatment("sb_rules")).to eq(1) + expect(context.treatment("sb_unaligned_rules")).to eq(1) + expect(published_exposures(context)).to eq([ + exposure(1, "sb_full_on", UNIT_TYPE, 1, ANCHOR, true, true, false, true, false, false, false), + exposure(2, "sb_rules", UNIT_TYPE, 1, ANCHOR, false, true, false, false, false, false, true), + exposure(3, "sb_unaligned_rules", UNIT_TYPE, 1, ANCHOR, false, true, false, false, false, false, true) + ]) + end + + it "never evaluates rules for an ineligible cluster" do + context = create_context([switchback(assignmentRules: ASSIGN_VARIANT_1, switchbackClusterValues: ["other-store"])]) + expect(context.treatment("exp_sb")).to eq(0) + expect(context.pending_count).to eq(0) + end + + # A split rule randomizes over the serving unit, not over the payload's unitType. + it "randomizes a split rule over the serving unit" do + rules = '{"rules":[{"type":"split","environments":[],"percentages":"50/50"}]}' + ones = 0 + 32.times do |u| + uid = "store-#{u}" + expected = VariantAssigner.new(uid).assign([0.5, 0.5], SEED_HI, SEED_LO) + context = create_context([switchback(unitType: "user_id", assignmentRules: rules)], + units: { UNIT_TYPE => uid, "user_id" => "fixed-user" }) + expect(context.treatment("exp_sb")).to eq(expected), uid + expect(published_exposures(context)).to eq([rule_exposure("exp_sb", expected, ANCHOR)]) + ones += expected + end + expect(ones).to be_between(1, 31) + end + + it "records a strict audience mismatch as control" do + context = create_context([switchback(audience: STRICT_GOLD_AUDIENCE, audienceStrict: true)]) + clock.now = ANCHOR + HOUR + expect(context.treatment("exp_sb")).to eq(0) + expect(published_exposures(context)).to eq([strict_mismatch_exposure(ANCHOR + HOUR)]) + end + + # Period 1 draws 1, so the variant 0 below is the strict mismatch's control. + it "serializes a strict audience mismatch exposure exactly" do + context = create_context([switchback(audience: STRICT_GOLD_AUDIENCE, audienceStrict: true)]) + expect(EXPECTED_2_ARMS[1]).to eq(1) + clock.now = ANCHOR + HOUR + 5 + context.treatment("exp_sb") + clock.now = ANCHOR + HOUR + 9 + + expect(JSON.parse(serialized_publish(context))).to eq( + "publishedAt" => ANCHOR + HOUR + 9, "units" => [{ "type" => UNIT_TYPE, "uid" => UID_HASH }], "hashed" => true, + "exposures" => [{ "id" => 1, "name" => "exp_sb", "unit" => UNIT_TYPE, "exposedAt" => ANCHOR + HOUR + 5, + "variant" => 0, "assigned" => false, "eligible" => true, "overridden" => false, + "fullOn" => false, "custom" => false, "audienceMismatch" => true, + "ruleOverride" => false }], + "attributes" => [{ "name" => CLUSTER_PATH, "value" => CLUSTER_KEY, "setAt" => ANCHOR }] + ) + end + + # The audience comes before the period check, so a strict mismatch before the anchor or with an + # unservable schedule is recorded. + it "records a strict audience mismatch before the anchor and on an unservable schedule" do + clock.now = ANCHOR - 1 + context = create_context([switchback(audience: STRICT_GOLD_AUDIENCE, audienceStrict: true)]) + expect(context.treatment("exp_sb")).to eq(0) + expect(published_exposures(context)).to eq([strict_mismatch_exposure(ANCHOR - 1)]) + + clock.now = ANCHOR + HOUR + 3 + context = create_context([switchback(audience: STRICT_GOLD_AUDIENCE, audienceStrict: true, + switchbackStartAt: nil)]) + expect(context.treatment("exp_sb")).to eq(0) + expect(published_exposures(context)).to eq([strict_mismatch_exposure(ANCHOR + HOUR + 3)]) + end + + # The legacy path returns an ineligible control before the audience is evaluated. + it "records nothing for a strict mismatch with a missing or unreadable cluster map" do + [nil, { UNIT_TYPE => "'geo" }].each do |clusters| + clock.now = ANCHOR + HOUR + 3 + context = create_context([switchback(audience: STRICT_GOLD_AUDIENCE, audienceStrict: true, + switchbackClusters: clusters)]) + expect(context.treatment("exp_sb")).to eq(0) + expect(context.pending_count).to eq(0), clusters.inspect + end + end + + # A strict-mismatched switchback is not assigned, so on a shared variable key the next + # experiment that declares the key wins, as for a unit experiment, and only the winner is + # exposed, as java-sdk does. + it "gives way on a shared variable key when strict-mismatched" do + sb = switchback(audience: STRICT_GOLD_AUDIENCE, audienceStrict: true) + unit = unit_twin(switchback(2, "exp_unit", 2, HOUR, fullOnVariant: 1, + variants: [{ name: "A", config: '{"sb.arm":10}' }, + { name: "B", config: '{"sb.arm":11}' }])) + clock.now = ANCHOR + HOUR + 3 + context = create_context([sb, unit]) + expect(context.variable_keys_list).to eq({ "sb.arm": %w[exp_sb exp_unit] }) + + expect(context.peek_variable_value("sb.arm", -1)).to eq(11) + expect(context.pending_count).to eq(0) + expect(context.variable_value("sb.arm", -1)).to eq(11) + expect(published_exposures(context)).to eq([ + exposure(2, "exp_unit", UNIT_TYPE, 1, ANCHOR + HOUR + 3, true, true, false, true, false, false, false) + ]) + end + + it "returns the default value for a strict-mismatched switchback alone on a variable key" do + clock.now = ANCHOR + HOUR + 3 + context = create_context([switchback(audience: STRICT_GOLD_AUDIENCE, audienceStrict: true)]) + expect(context.peek_variable_value("sb.arm", -1)).to eq(-1) + expect(context.pending_count).to eq(0) + expect(context.variable_value("sb.arm", -1)).to eq(-1) + end + + # The SWITCHBACK.md "Exposure flags" table: [assigned, eligible, overridden, full_on, custom, + # audience_mismatch, rule_override], and the variant served at ANCHOR + 2h + 3 (period 2, whose + # 3-arm draw is 1). Forced variants are 2, which differs from both control and the draw. + PARITY = { + override: [[false, true, true, false, false, false, false], 2], + override_over_strict_mismatch: [[false, true, true, false, false, false, false], 2], + rule: [[false, true, false, false, false, false, true], 2], + rule_over_strict_mismatch: [[false, true, false, false, false, false, true], 2], + strict_mismatch: [[false, true, false, false, false, true, false], 0], + strict_mismatch_over_full_on: [[false, true, false, false, false, true, false], 0], + strict_mismatch_over_traffic_miss: [[false, true, false, false, false, true, false], 0], + non_strict_mismatch: [[true, true, false, false, false, true, false], EXPECTED_3_ARMS[2]], + full_on: [[true, true, false, true, false, false, false], 2], + traffic_miss: [[true, false, false, false, false, false, false], 0], + custom: [[true, true, false, false, true, false, false], 2], + draw: [[true, true, false, false, false, false, false], EXPECTED_3_ARMS[2]] + }.freeze + + def configure_branch(branch, experiment) + strict = { audience: STRICT_GOLD_AUDIENCE, audienceStrict: true } + extra = case branch + when :override_over_strict_mismatch, :strict_mismatch then strict + when :rule_over_strict_mismatch then strict.merge(assignmentRules: ASSIGN_VARIANT_2) + when :rule then { assignmentRules: ASSIGN_VARIANT_2 } + when :strict_mismatch_over_full_on then strict.merge(fullOnVariant: 2) + when :strict_mismatch_over_traffic_miss then strict.merge(trafficSplit: [1.0, 0.0]) + when :non_strict_mismatch then { audience: STRICT_GOLD_AUDIENCE } + when :full_on then { fullOnVariant: 2 } + when :traffic_miss then { trafficSplit: [1.0, 0.0] } + else {} + end + experiment.merge(extra) + end + + def expose_once(experiment, branch) + overrides = %i[override override_over_strict_mismatch].include?(branch) ? { "exp_parity" => 2 } : {} + custom = branch == :custom ? { "exp_parity" => 2 } : {} + context = create_context([configure_branch(branch, experiment)], overrides: overrides, custom: custom) + context.treatment("exp_parity") + exposures = published_exposures(context) + expect(exposures.length).to eq(1), branch.to_s + exposures[0] + end + + def flags(e) + [e.assigned, e.eligible, e.overridden, e.full_on, e.custom, e.audience_mismatch, e.rule_override] + end + + PARITY.each do |branch, (expected_flags, expected_variant)| + it "publishes the same exposure flags as a unit experiment for #{branch}" do + clock.now = ANCHOR + 2 * HOUR + 3 + expect(EXPECTED_3_ARMS[2]).to eq(1) + + unit = expose_once(unit_twin(switchback(1, "exp_parity", 3)), branch) + sb = expose_once(switchback(1, "exp_parity", 3), branch) + + expect(flags(unit)).to eq(expected_flags) + expect(flags(sb)).to eq(expected_flags) + expect(sb.variant).to eq(expected_variant) + expect(unit.variant).to eq(expected_variant) unless %i[draw non_strict_mismatch].include?(branch) + expect([sb.id, sb.name, sb.exposed_at]).to eq([unit.id, unit.name, unit.exposed_at]) + end + end + + it "records a traffic miss on an eligible cluster as an ineligible exposure" do + context = create_context([switchback(1, "exp_miss", 2, HOUR, trafficSplit: [1.0, 0.0]), + switchback(2, "exp_cluster_ineligible", 2, HOUR, trafficSplit: [1.0, 0.0], + switchbackClusterValues: ["other-store"])]) + clock.now = ANCHOR + 2 * HOUR + 3 + expect(context.treatment("exp_miss")).to eq(0) + expect(context.treatment("exp_cluster_ineligible")).to eq(0) + expect(published_exposures(context)).to eq([sb_exposure(1, "exp_miss", 0, ANCHOR + 2 * HOUR + 3, true, false)]) + end + + it "keeps custom field and unit lookups working" do + context = create_context([switchback]) + expect(context.get_unit(UNIT_TYPE)).to eq(UID) + expect(context.custom_field_keys).to eq([]) + expect(context.custom_field_value("exp_sb", "missing")).to be_nil + end + + it "bounds the per-period cache" do + context = create_context([switchback]) + 50.times do |i| + clock.now = ANCHOR + i * HOUR + context.treatment("exp_sb") + end + expect(context.send(:assignment_cache).size).to eq(2) + expect(context.pending_count).to eq(50) + end + + it "never uses unitType to assign a switchback" do + context = create_context([switchback(unitType: "user_id")], units: { UNIT_TYPE => UID, "user_id" => "u1" }) + 3.times do |i| + clock.now = ANCHOR + i * HOUR + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[i]) + end + expect(published_exposures(context).map(&:unit)).to eq([UNIT_TYPE] * 3) + end + + # The publish payload has no switchback-specific fields; the cluster attribute is published + # with its timestamp, since the Collector re-resolves the cluster at exposedAt. + it "adds no fields to the publish payload" do + context = create_context([switchback]) + clock.now = ANCHOR + 5 + context.treatment("exp_sb") + clock.now = ANCHOR + HOUR + 7 + context.treatment("exp_sb") + clock.now = ANCHOR + HOUR + 9 + + exposure_json = lambda do |variant, at| + { "id" => 1, "name" => "exp_sb", "unit" => UNIT_TYPE, "exposedAt" => at, "variant" => variant, + "assigned" => true, "eligible" => true, "overridden" => false, "fullOn" => false, "custom" => false, + "audienceMismatch" => false, "ruleOverride" => false } + end + json = serialized_publish(context) + expect(json).to eq(JSON.generate( + publishedAt: ANCHOR + HOUR + 9, units: [{ type: UNIT_TYPE, uid: UID_HASH }], hashed: true, + exposures: [exposure_json.call(EXPECTED_2_ARMS[0], ANCHOR + 5), + exposure_json.call(EXPECTED_2_ARMS[1], ANCHOR + HOUR + 7)], + attributes: [{ name: CLUSTER_PATH, value: CLUSTER_KEY, setAt: ANCHOR }] + )) + expect(EXPECTED_2_ARMS[0]).not_to eq(EXPECTED_2_ARMS[1]) + end + + it "keeps one exposure per period across flushes" do + context = create_context([switchback]) + clock.now = ANCHOR + context.treatment("exp_sb") + context.publish + clock.now = ANCHOR + 1 + context.treatment("exp_sb") + expect(context.pending_count).to eq(0) + clock.now = ANCHOR + HOUR + context.treatment("exp_sb") + context.publish + + events = context.send(:event_handler).events + expect(events.length).to eq(2) + expect(events.flat_map(&:exposures).map(&:variant)).to eq([EXPECTED_2_ARMS[0], EXPECTED_2_ARMS[1]]) + end + + # The clock crosses into period 1 after the first read; the exposure keeps the instant that + # selected period 0. + it "stamps a treatment exposure with the resolution instant" do + context = create_context([switchback]) + clock.now = ANCHOR + HOUR + clock.next_read = ANCHOR + HOUR - 1 + + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(published_exposures(context)).to eq([sb_exposure(1, "exp_sb", EXPECTED_2_ARMS[0], ANCHOR + HOUR - 1, + true, true)]) + end + + it "stamps a variable exposure with the resolution instant" do + # A holdout with all traffic in arm 1; holdouts never fire through a switchback. + context = create_context([switchback(holdoutIds: [11])], holdouts: [holdout([0.0, 1.0])]) + clock.now = ANCHOR + HOUR + clock.next_read = ANCHOR + HOUR - 1 + + expect(context.variable_value("sb.arm", -1)).to eq(EXPECTED_2_ARMS[0]) + expect(published_exposures(context)).to eq([sb_exposure(1, "exp_sb", EXPECTED_2_ARMS[0], ANCHOR + HOUR - 1, + true, true)]) + end + + # A peek caches the slot without exposing; the later treatment exposes at its own instant. + it "stamps an exposure after a peek with the exposing call's instant" do + context = create_context([switchback]) + clock.now = ANCHOR + 10 + expect(context.peek_treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + clock.now = ANCHOR + 20 * 60_000 + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(published_exposures(context)).to eq([sb_exposure(1, "exp_sb", EXPECTED_2_ARMS[0], ANCHOR + 20 * 60_000, + true, true)]) + end + + # A switchback elsewhere in the payload makes the call read the clock up front. + # The exposing call's reading does not outlive the call: a later direct queue_exposure (a public + # method) stamps its own reading. + it "does not leak an exposing call's instant into a later queue_exposure" do + context = create_context([switchback, switchback(2, "exp_other")]) + clock.now = ANCHOR + 5 + context.treatment("exp_other") + clock.now = ANCHOR + 9 + peeked = context.send(:assignment, "exp_sb", ANCHOR + 9) + context.queue_exposure(peeked) + expect(published_exposures(context).map(&:exposed_at)).to eq([ANCHOR + 5, ANCHOR + 9]) + end + + it "keeps stamping unit experiments at enqueue time" do + context = create_context([switchback(randomizationType: "unit"), switchback(2, "exp_other")]) + clock.now = ANCHOR + HOUR + clock.next_read = ANCHOR + HOUR - 1 + + variant = context.treatment("exp_sb") + expect(published_exposures(context)).to eq([sb_exposure(1, "exp_sb", variant, ANCHOR + HOUR, true, true)]) + end + + # A grid change that lowers the current index below the retained ones must not evict the slot + # it just installed. + it "exposes once after a grid refresh to a lower index" do + context = create_context([switchback]) + clock.now = ANCHOR + 99 * HOUR + context.treatment("exp_sb") + clock.now = ANCHOR + 100 * HOUR + context.treatment("exp_sb") + expect(context.pending_count).to eq(2) + + refresh_to(context, [switchback(switchbackStartAt: ANCHOR + 100 * HOUR)]) + 3.times { expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) } + expect(context.pending_count).to eq(3) + end + + it "exposes once after a period length refresh to a lower index" do + context = create_context([switchback]) + clock.now = ANCHOR + 100 * HOUR + context.treatment("exp_sb") + clock.now = ANCHOR + 101 * HOUR + context.treatment("exp_sb") + + refresh_to(context, [switchback(1, "exp_sb", 2, 200 * HOUR)]) + 2.times { context.treatment("exp_sb") } + expect(context.pending_count).to eq(3) + end + + it "re-exposes an evicted period at most once after a clock rewind" do + context = create_context([switchback]) + 3.times do |i| + clock.now = ANCHOR + i * HOUR + context.treatment("exp_sb") + end + expect(context.pending_count).to eq(3) + + clock.now = ANCHOR + 3.times { expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) } + expect(context.pending_count).to eq(4) + + # Retained {0, 2}: period 2 is still deduplicated, period 1 was evicted. + clock.now = ANCHOR + 2 * HOUR + context.treatment("exp_sb") + expect(context.pending_count).to eq(4) + clock.now = ANCHOR + HOUR + 3.times { expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[1]) } + expect(context.pending_count).to eq(5) + + exposures = published_exposures(context) + expect(exposures[3]).to eq(sb_exposure(1, "exp_sb", EXPECTED_2_ARMS[0], ANCHOR, true, true)) + expect(exposures[4]).to eq(sb_exposure(1, "exp_sb", EXPECTED_2_ARMS[1], ANCHOR + HOUR, true, true)) + end + + # An overridden slot is re-resolved on a grid change; the override still wins and the + # holdout never fires. + it "re-resolves an override when the grid changes" do + context = create_context([switchback(1, "exp_sb", 3, HOUR, holdoutIds: [11])], holdouts: [holdout([0.0, 1.0])]) + context.set_override("exp_sb", 2) + + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(2) + expect(context.variable_value("sb.arm", -1)).to eq(2) + expect(context.pending_count).to eq(1) + + # Same index 0 under the new period length; variant 2 now carries a different value. + regridded = switchback(1, "exp_sb", 3, 2 * HOUR, holdoutIds: [11]) + regridded[:variants][2] = { name: "C", config: '{"sb.arm":22}' } + refresh_to(context, [regridded], [holdout([0.0, 1.0])]) + + expect(context.treatment("exp_sb")).to eq(2) + expect(context.variable_value("sb.arm", -1)).to eq(22) + expect(context.pending_count).to eq(2) + expect(published_exposures(context)).to eq( + [exposure(1, "exp_sb", UNIT_TYPE, 2, ANCHOR + 10, false, true, true, false, false, false)] * 2 + ) + end + + # Each identity transition is a new epoch. + it "re-resolves after switchback to unit to an identical switchback" do + context = create_context([switchback]) + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(context.pending_count).to eq(1) + + refresh_to(context, [switchback(randomizationType: "unit")]) + context.treatment("exp_sb") + expect(context.pending_count).to eq(2) + + refresh_to(context, [switchback]) + 2.times { expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) } + expect(context.pending_count).to eq(3) + end + + it "re-resolves a removed and restored switchback" do + context = create_context([switchback]) + clock.now = ANCHOR + 10 + context.treatment("exp_sb") + + refresh_to(context, []) + expect(context.treatment("exp_sb")).to eq(0) + expect(context.pending_count).to eq(2) + + refresh_to(context, [switchback]) + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(context.pending_count).to eq(3) + end + + # The pre-anchor bare-name slot shares the lifecycle of the period slots. + it "drops the pre-anchor slot when the grid changes" do + grid_a = switchback(switchbackStartAt: ANCHOR + 10 * HOUR) + context = create_context([grid_a]) + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(0) + expect(context.pending_count).to eq(0) + + refresh_to(context, [switchback]) + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(context.pending_count).to eq(1) + + refresh_to(context, [grid_a]) + expect(context.treatment("exp_sb")).to eq(0) + expect(context.variable_value("sb.arm", -1)).to eq(0) + expect(context.pending_count).to eq(1) + end + + # Epochs are reconciled lazily; an intermediate state never looked up still ends the epoch. + it "re-resolves after transitions without an intervening lookup" do + context = create_context([switchback]) + clock.now = ANCHOR + 10 + context.treatment("exp_sb") + expect(context.pending_count).to eq(1) + + refresh_to(context, [switchback(randomizationType: "unit")]) + refresh_to(context, [switchback]) + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(context.pending_count).to eq(2) + + refresh_to(context, []) + refresh_to(context, [switchback]) + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(context.pending_count).to eq(3) + + refresh_to(context, [switchback(switchbackDesignType: "other")]) + refresh_to(context, [switchback]) + 2.times { expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) } + expect(context.pending_count).to eq(4) + + refresh_to(context, [switchback]) + context.treatment("exp_sb") + expect(context.pending_count).to eq(4) + end + + class CountingAudienceMatcher < AudienceMatcher + attr_accessor :rule_evaluations + + def initialize + super(DefaultAudienceDeserializer.new) + @rule_evaluations = 0 + end + + def evaluate_parsed_rules(*args) + @rule_evaluations += 1 + super + end + end + + # A unit experiment whose rule outcome changes after set_attribute: the cached read evaluates the + # rules and rejects the slot, and the rebuild evaluates them once more. Two evaluations. + it "evaluates the rules twice on a stale rule transition" do + us_rule = '{"rules":[{"type":"assign","environments":[],' \ + '"conditions":{"and":[{"eq":[{"var":"country"},{"value":"US"}]}]},"variant":1}]}' + matcher = CountingAudienceMatcher.new + context = create_context([switchback(randomizationType: "unit", assignmentRules: us_rule)], + audience_matcher: matcher) + context.peek_treatment("exp_sb") + expect(matcher.rule_evaluations).to eq(1) + + context.set_attribute("country", "US") + matcher.rule_evaluations = 0 + expect(context.peek_treatment("exp_sb")).to eq(1) + expect(matcher.rule_evaluations).to eq(2) + expect(context.peek_treatment("exp_sb")).to eq(1) + expect(matcher.rule_evaluations).to eq(2) + end + + # The same for a switchback with an eligible cluster, whose rules are re-checked like a unit's. + it "evaluates a switchback's rules twice on a stale rule transition and not again after" do + us_rule = '{"rules":[{"type":"assign","environments":[],' \ + '"conditions":{"and":[{"eq":[{"var":"country"},{"value":"US"}]}]},"variant":1}]}' + matcher = CountingAudienceMatcher.new + context = create_context([switchback(assignmentRules: us_rule)], audience_matcher: matcher) + clock.now = ANCHOR + HOUR + expect(context.peek_treatment("exp_sb")).to eq(EXPECTED_2_ARMS[1]) + expect(matcher.rule_evaluations).to eq(1) + + context.set_attribute("country", "US") + matcher.rule_evaluations = 0 + expect(context.peek_treatment("exp_sb")).to eq(1) + expect(matcher.rule_evaluations).to eq(2) + 3.times { expect(context.peek_treatment("exp_sb")).to eq(1) } + expect(matcher.rule_evaluations).to eq(2) + end + + # A legacy switchback serves under its declared unitType, so a unitType change is identity. + it "treats a unitType change on a legacy switchback as identity" do + context = create_context([switchback(switchbackClusters: nil)], units: { UNIT_TYPE => UID, "user_id" => "u1" }) + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(0) + expect(context.variable_value("sb.arm", -1)).to eq(0) + expect(context.send(:switchback_resolution_for_test, "exp_sb").unit_type).to eq(UNIT_TYPE) + + refresh_to(context, [switchback(switchbackClusters: nil, unitType: "other")]) + expect(context.treatment("exp_sb")).to eq(0) + expect(context.variable_value("sb.arm", -1)).to eq(-1) + + refresh_to(context, [switchback(switchbackClusters: nil, unitType: "user_id")]) + expect(context.treatment("exp_sb")).to eq(0) + expect(context.variable_value("sb.arm", -1)).to eq(0) + resolution = context.send(:switchback_resolution_for_test, "exp_sb") + expect([resolution.unit_type, resolution.eligible, resolution.switchback_silent]).to eq(["user_id", false, true]) + expect(context.pending_count).to eq(0) + end + + # An ineligible or absent slot never consulted its rules. + it "never re-evaluates rules for an ineligible or absent slot" do + matcher = CountingAudienceMatcher.new + ineligible = switchback(1, "exp_ineligible", 2, HOUR, assignmentRules: ASSIGN_VARIANT_1, + switchbackClusterValues: ["other-store"]) + absent = switchback(2, "exp_absent", 2, HOUR, assignmentRules: ASSIGN_VARIANT_1, + switchbackClusters: { "device_id" => CLUSTER_PATH }) + context = create_context([ineligible, absent], audience_matcher: matcher) + clock.now = ANCHOR + 10 + expect(context.treatment("exp_ineligible")).to eq(0) + expect(context.treatment("exp_absent")).to eq(0) + expect(matcher.rule_evaluations).to eq(0) + + context.set_attribute("x", 1) + changed = '{"rules":[{"type":"assign","environments":[],"variant":1,"name":"changed"}]}' + refresh_to(context, [ineligible.merge(assignmentRules: changed), absent.merge(assignmentRules: changed)]) + + expect(context.treatment("exp_ineligible")).to eq(0) + expect(context.treatment("exp_absent")).to eq(0) + expect(matcher.rule_evaluations).to eq(0) + expect(context.pending_count).to eq(0) + end + + # Rules are not switchback identity: no second exposure in the period. + it "keeps the variant and exposes once on an in-period rule refresh" do + context = create_context([switchback(assignmentRules: ASSIGN_VARIANT_1)]) + clock.now = ANCHOR + 5 + expect(context.treatment("exp_sb")).to eq(1) + + context.set_attribute("tier", "x") + refreshed = '{"rules":[{"type":"assign","environments":[],"variant":1,' \ + '"conditions":{"and":[{"eq":[{"var":"tier"},{"value":"x"}]}]}}]}' + refresh_to(context, [switchback(assignmentRules: refreshed)]) + clock.now = ANCHOR + 6 + expect(context.treatment("exp_sb")).to eq(1) + expect(published_exposures(context)).to eq([rule_exposure("exp_sb", 1, ANCHOR + 5)]) + end + + # SDK choice: before the anchor nothing is recorded, a traffic miss included. From the anchor + # the same miss is recorded. + it "keeps a pre-anchor traffic miss silent" do + clock.now = ANCHOR - 1 + context = create_context([switchback(trafficSplit: [1.0, 0.0])]) + expect(context.treatment("exp_sb")).to eq(0) + expect(context.pending_count).to eq(0) + + clock.now = ANCHOR + expect(context.treatment("exp_sb")).to eq(0) + expect(published_exposures(context)).to eq([sb_exposure(1, "exp_sb", 0, ANCHOR, true, false)]) + end + + # An override with no serving unit is exposed under the declared unitType on the legacy path. + it "exposes an override on a legacy switchback under the declared unitType" do + context = create_context([switchback(1, "exp_missing_map", 2, HOUR, unitType: "user_id", switchbackClusters: nil), + switchback(2, "exp_unreadable_map", 2, HOUR, unitType: "user_id", + switchbackClusters: { UNIT_TYPE => "'unterminated" })], + overrides: { "exp_missing_map" => 1, "exp_unreadable_map" => 1 }) + clock.now = ANCHOR + 5 + expect(context.treatment("exp_missing_map")).to eq(1) + expect(context.treatment("exp_unreadable_map")).to eq(1) + + expect(published_exposures(context)).to eq([ + exposure(1, "exp_missing_map", "user_id", 1, ANCHOR + 5, false, true, true, false, false, false), + exposure(2, "exp_unreadable_map", "user_id", 1, ANCHOR + 5, false, true, true, false, false, false) + ]) + end + + it "serializes a rule-won and a traffic-miss exposure exactly" do + context = create_context([switchback(1, "exp_rule", 2, HOUR, assignmentRules: ASSIGN_VARIANT_1), + switchback(2, "exp_miss", 2, HOUR, trafficSplit: [1.0, 0.0])]) + clock.now = ANCHOR + 5 + context.treatment("exp_rule") + context.treatment("exp_miss") + clock.now = ANCHOR + 9 + + flags = lambda do |assigned, eligible, rule| + { "assigned" => assigned, "eligible" => eligible, "overridden" => false, "fullOn" => false, + "custom" => false, "audienceMismatch" => false, "ruleOverride" => rule } + end + expect(JSON.parse(serialized_publish(context))).to eq( + "publishedAt" => ANCHOR + 9, "units" => [{ "type" => UNIT_TYPE, "uid" => UID_HASH }], "hashed" => true, + "exposures" => [ + { "id" => 1, "name" => "exp_rule", "unit" => UNIT_TYPE, "exposedAt" => ANCHOR + 5, "variant" => 1 } + .merge(flags.call(false, true, true)), + { "id" => 2, "name" => "exp_miss", "unit" => UNIT_TYPE, "exposedAt" => ANCHOR + 5, "variant" => 0 } + .merge(flags.call(true, false, false)) + ], + "attributes" => [{ "name" => CLUSTER_PATH, "value" => CLUSTER_KEY, "setAt" => ANCHOR }] + ) + end + + # Audience evaluation runs under the assignment lock; refreshing from inside it must not deadlock. + class RefreshingAudienceMatcher < AudienceMatcher + attr_accessor :context, :refresh_next + + def initialize + super(DefaultAudienceDeserializer.new) + end + + def evaluate(_audience, _attributes) + if @refresh_next + @refresh_next = false + context.refresh + end + AudienceMatcher::Result.new(true) + end + end + + it "does not deadlock when audience evaluation refreshes the context" do + matcher = RefreshingAudienceMatcher.new + experiment = switchback(audience: '{"filter":[{"value":true}]}') + context = create_context([experiment], audience_matcher: matcher) + matcher.context = context + allow(provider).to receive(:context_data).and_return(ready(data_of([experiment]))) + + primed = context.treatment("exp_sb") + context.set_attribute("country", "PT") + matcher.refresh_next = true + worker = Thread.new { context.treatment("exp_sb") } + expect(worker.join(10)).not_to be_nil + expect(worker.value).to eq(primed) + expect(provider).to have_received(:context_data).once + expect(context.pending_count).to eq(1) + end + + # The slot keeps the key read first (Lisboa) while other threads keep setting the attribute + # and the audience is re-evaluated; Faro draws differently in period 1. + it "exposes once and keeps the key under concurrent resolution and set_attribute" do + context = create_context([switchback(audience: '{"filter":[{"value":true}]}', + switchbackClusters: { UNIT_TYPE => "city" })]) + clock.now = ANCHOR + HOUR + 10 + context.set_attribute("city", "Lisboa") + lisboa = draw("Lisboa", 1, SEED_HI, SEED_LO, 2) + expect(draw("Faro", 1, SEED_HI, SEED_LO, 2)).not_to eq(lisboa) + expect(context.peek_treatment("exp_sb")).to eq(lisboa) + + stop = Queue.new + writer = Thread.new do + context.set_attribute("city", "Faro") while stop.empty? + end + begin + readers = Array.new(4) { Thread.new { Array.new(200) { context.treatment("exp_sb") } } } + variants = readers.flat_map(&:value) + ensure + # A failing reader still stops the writer, and a stalled writer fails the example. + stop << true + expect(writer.join(10)).not_to be_nil + end + + expect(variants.uniq).to eq([lisboa]) + expect(context.pending_count).to eq(1) + end + + # An exposed override of a switchback without a linked unit is kept when a unit is set: it + # published, so replacing it would publish the override again. + it "keeps an exposed override when a linked unit is set later" do + context = create_context([switchback], units: { "user_id" => "u1" }, overrides: { "exp_sb" => 1 }) + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(1) + context.set_unit(UNIT_TYPE, UID) + expect(context.treatment("exp_sb")).to eq(1) + expect(context.pending_count).to eq(1) + expect(published_exposures(context).map(&:unit)).to eq([UNIT_TYPE]) + end + + # A peeked (unexposed) override of a switchback without a linked unit is resolved again once a + # linked unit is set, so its exposure goes under that unit, not the first linked type. + it "publishes a peeked override under the linked unit set later" do + experiment = switchback(switchbackClusters: { UNIT_TYPE => "city", "city_id" => "ccity" }) + context = create_context([experiment], units: { "user_id" => "u1" }, overrides: { "exp_sb" => 1 }) + clock.now = ANCHOR + 10 + expect(context.peek_treatment("exp_sb")).to eq(1) + context.set_unit("city_id", "c1") + context.set_attribute("ccity", "Lisboa") + expect(context.treatment("exp_sb")).to eq(1) + expect(published_exposures(context).map(&:unit)).to eq(["city_id"]) + end + + # Revalidating a split rule after set_attribute randomizes over the serving unit again, not the + # declared unitType (which has no unit here, and would give the no-unit variant 0). + it "revalidates a split rule over the serving unit" do + rule = '{"rules":[{"type":"split","environments":[],"percentages":"0/0/100"}]}' + context = create_context([switchback(1, "exp_sb", 3, HOUR, unitType: "user_id", assignmentRules: rule)]) + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(2) + context.set_attribute("unrelated", 1) + expect(context.treatment("exp_sb")).to eq(2) + expect(context.pending_count).to eq(1) + end + + it "serves a custom assignment changed within the period" do + context = create_context([switchback(1, "exp_sb", 3)], custom: { "exp_sb" => 2 }) + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(2) + context.set_custom_assignment("exp_sb", 1) + expect(context.treatment("exp_sb")).to eq(1) + expect(published_exposures(context).map { |e| [e.variant, e.custom] }).to eq([[2, true], [1, true]]) + end + + # The attribute map is built only for rules or an audience. + it "builds no attribute map for a switchback without rules or an audience" do + context = create_context([switchback]) + allow(context).to receive(:attributes_map).and_call_original + 3.times do |i| + clock.now = ANCHOR + i * HOUR + context.treatment("exp_sb") + end + expect(context).not_to have_received(:attributes_map) + end + + # Slots are invalidated by the generation alone, so a cached read builds no grid. + it "builds no grid on a cached read" do + context = create_context([switchback]) + clock.now = ANCHOR + 10 + context.treatment("exp_sb") + allow(context).to receive(:switchback_grid).and_call_original + 100.times { context.peek_treatment("exp_sb") } + expect(context).not_to have_received(:switchback_grid) + end + + it "exposes once when many threads resolve the same period" do + context = create_context([switchback]) + clock.now = ANCHOR + HOUR + 10 + threads = Array.new(8) { Thread.new { 50.times.map { context.treatment("exp_sb") } } } + expect(threads.flat_map(&:value).uniq).to eq([EXPECTED_2_ARMS[1]]) + expect(context.pending_count).to eq(1) + end + end +end + +# No cost without switchbacks: a payload without one never reads the clock on +# treatment, peek or variable reads, and builds no switchback state. +module ContextSwitchbackCostSpec + RSpec.describe "Context without switchbacks" do + include SwitchbackSpecSupport + + let(:clock) { SwitchbackSpecSupport::MutableClock.new(SwitchbackSpecSupport::ANCHOR) } + + # As in 1.4.0, reads never route exposures through the public queue_exposure, with a + # switchback in the payload too; a direct call queues what it is given at its own reading. + it "keeps reads off a queue_exposure override when switchbacks are served" do + subclass = Class.new(Context) do + attr_reader :queued + + def queue_exposure(assignment) + (@queued ||= []) << assignment.name + super + end + end + json = JSON.generate(experiments: [ + { id: 1, name: "exp_unit", unitType: "store_id", iteration: 1, seedHi: 1, seedLo: 2, split: [0.5, 0.5], + trafficSeedHi: 1, trafficSeedLo: 2, trafficSplit: [0.0, 1.0], fullOnVariant: 0, applications: [], + variants: [{ name: "A", config: nil }, { name: "B", config: nil }] }, + { id: 2, name: "exp_sb", unitType: "store_id", iteration: 1, seedHi: -5, seedLo: -7, split: [0.5, 0.5], + trafficSeedHi: 1, trafficSeedLo: 2, trafficSplit: [0.0, 1.0], fullOnVariant: 0, applications: [], + variants: [{ name: "A", config: nil }, { name: "B", config: nil }], randomizationType: "switchback", + switchbackClusters: { store_id: "store_key" }, switchbackStartAt: SwitchbackSpecSupport::ANCHOR, + switchbackPeriodMs: SwitchbackSpecSupport::HOUR } + ]) + data = DefaultContextDataDeserializer.new.deserialize(json, 0, json.length) + config = ContextConfig.create + config.set_units(store_id: "s1") + config.set_attributes(store_key: "store-42") + publisher = SwitchbackSpecSupport::Publisher.new + context = subclass.new(clock, config, ready(data), nil, publisher, nil, + DefaultVariableParser.new, AudienceMatcher.new(DefaultAudienceDeserializer.new)) + clock.now = SwitchbackSpecSupport::ANCHOR + SwitchbackSpecSupport::HOUR + clock.next_read = SwitchbackSpecSupport::ANCHOR + SwitchbackSpecSupport::HOUR - 1 + expect(context.treatment("exp_sb")).to eq(draw("store-42", 0, -5, -7, 2)) + context.treatment("exp_unit") + expect(context.queued).to be_nil + context.publish + expect(publisher.events[0].exposures.map(&:exposed_at)) + .to eq([SwitchbackSpecSupport::ANCHOR + SwitchbackSpecSupport::HOUR - 1, + SwitchbackSpecSupport::ANCHOR + SwitchbackSpecSupport::HOUR]) + end + + # A fixed Time is converted to milliseconds once, so cached reads allocate nothing for it. + it "converts a fixed Time once" do + context = Context.create(Time.at(1_620_000_000), ContextConfig.create, ready(data_of([])), nil, nil, nil, + DefaultVariableParser.new, AudienceMatcher.new(DefaultAudienceDeserializer.new)) + clock_time = context.send(:clock) + allow(clock_time).to receive(:to_r).and_call_original + 3.times { context.set_attribute("a", 1) } + expect(clock_time).to have_received(:to_r).once + end + + it "reads no clock on the assignment paths" do + json = File.read(File.join(__dir__, "fixtures", "resources", "context.json")) + data = DefaultContextDataDeserializer.new.deserialize(json, 0, json.length) + context = build_context(data, units: { session_id: "e791e240fcd3df7d238cfc285f475e8152fcc0ec", user_id: "1" }) + context.peek_treatment("exp_test_ab") + allow(clock).to receive(:call).and_call_original + context.treatment("exp_test_ab") + context.peek_treatment("exp_test_ab") + context.variable_value("banner.border", 0) + context.peek_variable_value("banner.border", 0) + # Only the exposure itself reads the clock, once. + expect(clock).to have_received(:call).once + %i[expose_assignment separate_switchback_exposures].each do |helper| + allow(context).to receive(helper).and_call_original + end + context.treatment("exp_test_ab") + context.peek_treatment("exp_test_ab") + context.variable_value("banner.border", 0) + context.publish + expect(context).not_to have_received(:expose_assignment) + expect(context).not_to have_received(:separate_switchback_exposures) + expect(context.instance_variable_get(:@switchback_epochs)).to be_empty + end + end +end diff --git a/spec/experiment_switchback_fields_spec.rb b/spec/experiment_switchback_fields_spec.rb new file mode 100644 index 00000000..6cc58524 --- /dev/null +++ b/spec/experiment_switchback_fields_spec.rb @@ -0,0 +1,92 @@ +# frozen_string_literal: true + +require "json" +require "default_context_data_deserializer" +require "json/experiment" + +# Ports of java-sdk ExperimentSwitchbackFieldsTest and the switchback cases of +# DefaultContextDataDeserializerTest. +RSpec.describe "Experiment switchback fields" do + def switchback(**overrides) + Experiment.new({ + id: 1, name: "exp", unitType: "store_id", randomizationType: "switchback", + switchbackClusters: { store_id: "store/key", device_id: "geo/city" }, + switchbackClusterValues: %w[porto lisbon], switchbackStartAt: 1_767_225_600_000, + switchbackPeriodMs: 3_600_000, switchbackCarryoverDurationMs: 900_000, switchbackBurnInDurationMs: 600_000, + switchbackBurnOutDurationMs: 0, switchbackDesignType: "balanced_block", + switchbackEstimand: "global_average_treatment_effect" + }.merge(overrides)) + end + + it "compares every switchback field, and the cluster order" do + expect(switchback).to eq(switchback) + [ + { randomizationType: "unit" }, + { switchbackClusters: nil }, + { switchbackClusters: { store_id: "store/key" } }, + { switchbackClusters: { store_id: "store/key", device_id: "geo/country" } }, + # Same entries, other order: the order is semantic. + { switchbackClusters: { device_id: "geo/city", store_id: "store/key" } }, + { switchbackClusterValues: nil }, + { switchbackClusterValues: %w[lisbon porto] }, + { switchbackStartAt: 1_767_229_200_000 }, + { switchbackPeriodMs: 86_400_000 }, + { switchbackCarryoverDurationMs: nil }, + { switchbackBurnInDurationMs: 1 }, + { switchbackBurnOutDurationMs: 1 }, + { switchbackDesignType: "other" }, + { switchbackEstimand: "other" } + ].each do |mutation| + changed = switchback(**mutation) + expect(changed).not_to eq(switchback), mutation.inspect + expect(switchback).not_to eq(changed), mutation.inspect + end + end + + it "reads camelCase and snake_case keys alike" do + snake = Experiment.new(id: 1, name: "exp", unit_type: "store_id", randomization_type: "switchback", + switchback_clusters: { "store_id" => "store/key", "device_id" => "geo/city" }, + switchback_cluster_values: %w[porto lisbon], switchback_start_at: 1_767_225_600_000, + switchback_period_ms: 3_600_000, switchback_carryover_duration_ms: 900_000, + switchback_burn_in_duration_ms: 600_000, switchback_burn_out_duration_ms: 0, + switchback_design_type: "balanced_block", + switchback_estimand: "global_average_treatment_effect") + expect(snake).to eq(switchback) + end + + def deserialize(json) + DefaultContextDataDeserializer.new.deserialize(json, 0, json.length) + end + + it "deserializes every switchback field and ignores the Phase 1E and unknown ones" do + data = deserialize(resource("switchback_context.json")) + sb, unit = data.experiments + + expect([sb.randomization_type, sb.switchback_cluster_values, sb.switchback_start_at, sb.switchback_period_ms, + sb.switchback_carryover_duration_ms, sb.switchback_burn_in_duration_ms, sb.switchback_burn_out_duration_ms, + sb.switchback_design_type, sb.switchback_estimand]) + .to eq(["switchback", %w[porto lisbon], 1_767_225_600_000, 3_600_000, 900_000, 600_000, 0, "balanced_block", + "global_average_treatment_effect"]) + # The declared order survives deserialization; it is not sorted. + expect(sb.switchback_clusters.to_a).to eq([[:store_id, "store/key"], [:device_id, "geo/city"]]) + %i[@switchback_cluster_count @switchback_cluster_attribute @switchback_cluster_unit_type + @switchback_future_field].each do |ivar| + expect(sb.instance_variable_defined?(ivar)).to be(false), ivar.to_s + end + expect([unit.randomization_type, unit.switchback_start_at, unit.switchback_clusters]).to eq(["unit", nil, nil]) + end + + it "keeps the cluster order of the payload" do + json = '{"experiments":[{"id":1,"name":"exp","randomizationType":"switchback",' \ + '"switchbackClusters":{"z_type":"a","a_type":"b","m_type":"c"}}]}' + experiment = deserialize(json).experiments[0] + expect(experiment.switchback_clusters.keys).to eq(%i[z_type a_type m_type]) + expect(experiment.switchback_cluster_values).to be_nil + end + + it "leaves the switchback fields nil without them" do + deserialize(resource("context.json")).experiments.each do |experiment| + expect(experiment.switchback_fields).to all(be_nil) + end + end +end diff --git a/spec/fixtures/resources/switchback/attribute-path-cases.json b/spec/fixtures/resources/switchback/attribute-path-cases.json new file mode 100644 index 00000000..7b1d3fed --- /dev/null +++ b/spec/fixtures/resources/switchback/attribute-path-cases.json @@ -0,0 +1,16 @@ +{ + "description": "Cluster attribute paths read by both the Collector (SwitchbackAttributePath) and analysis (ClickHouseSwitchbackExpr). An unquoted segment is an array index exactly when Guava Ints.tryParse parses it (no '+', ASCII digits only). supported: accepted by isSupported and by requireSupportedAttributePath; a negative index is unsupported because ClickHouse throws ZERO_ARRAY_OR_TUPLE_INDEX on the [0] subscript pathToArgs renders for it. value: what the path resolves to in attributes; null means missing (no cluster key).", + "attributes": { + "items": [{ "city": "Lisbon" }, { "city": "Faro" }], + "geo": { "city": "Porto", "-1": "minus-one-key", "+1": "plus-one-key" } + }, + "cases": [ + { "path": "items/0/city", "supported": true, "value": "Lisbon" }, + { "path": "items/+0/city", "supported": true, "value": null }, + { "path": "items/-1/city", "supported": false, "value": null }, + { "path": "geo/-1", "supported": false, "value": null }, + { "path": "geo/+1", "supported": true, "value": "plus-one-key" }, + { "path": "items/\u0660/city", "supported": true, "value": null }, + { "path": "geo/city", "supported": true, "value": "Porto" } + ] +} diff --git a/spec/fixtures/resources/switchback/golden-vectors.json b/spec/fixtures/resources/switchback/golden-vectors.json new file mode 100644 index 00000000..b314abeb --- /dev/null +++ b/spec/fixtures/resources/switchback/golden-vectors.json @@ -0,0 +1,1392 @@ +{ + "assignSwitchback": [ + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "123456789", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "123456789", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "123456789", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "123456789", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "123456789", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "0", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "0", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "0", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "0", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "0", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "0", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "0", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "0", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "0", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "0", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "0", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "0", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "0", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "0", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "1", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "1", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "1", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "1", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "1", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "1", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "1", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "1", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "1", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "42", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "42", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "42", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "42", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "42", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "42", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "42", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "42", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "42", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "42", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "42", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "42", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "42", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "42", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "-1", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "-1", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "-1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "-1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "-1", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "-1", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "-1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "-1", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "-1", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "-1", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "-1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "-1", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "-1", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "-1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "123456789", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "123456789", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "123456789", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "123456789", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "123456789", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "123456789", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "123456789", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "123456789", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "123456789", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "123456789", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "123456789", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "123456789", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "123456789", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "123456789", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_1", "periodIndex": "0", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "1", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "2", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "5", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "9", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_1", "periodIndex": "10", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "11", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_1", "periodIndex": "23", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_1", "periodIndex": "100", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_1", "periodIndex": "-1", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_1", "periodIndex": "-2", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_1", "periodIndex": "-11", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_1", "periodIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_1", "periodIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "123456789", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "123456789", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "0", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "0", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "0", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "0", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "0", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "0", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "0", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "0", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "0", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "0", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "0", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "0", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "0", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "0", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "1", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "1", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "1", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "1", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "1", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "1", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "1", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "1", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "42", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "42", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "42", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "42", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "42", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "42", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "42", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "42", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "42", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "42", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "42", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "42", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "42", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "42", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "-1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "-1", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "-1", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "-1", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "-1", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "-1", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "-1", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "-1", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "-1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "-1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "-1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "-1", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "-1", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "-1", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "123456789", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "123456789", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "123456789", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "123456789", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "123456789", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "123456789", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "123456789", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "123456789", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "123456789", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "123456789", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "123456789", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "123456789", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "123456789", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "123456789", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "0", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "1", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": "market_2", "periodIndex": "2", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": "market_2", "periodIndex": "5", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_2", "periodIndex": "9", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": "market_2", "periodIndex": "10", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": "market_2", "periodIndex": "11", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_2", "periodIndex": "23", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": "market_2", "periodIndex": "100", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "-1", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": "market_2", "periodIndex": "-2", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": "market_2", "periodIndex": "-11", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": "market_2", "periodIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": "market_2", "periodIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "0", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "0", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "42", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "42", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "-1", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "-1", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "123456789", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "123456789", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 2, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "0", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "0", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "0", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "42", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "42", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "42", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "-1", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "-1", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "-1", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "123456789", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "123456789", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "123456789", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "123456789", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 3, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "0", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "0", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "0", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "0", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "0", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "0", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "0", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "0", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "0", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "0", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "0", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "0", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "0", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "0", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "1", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "1", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "1", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "1", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "1", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "1", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "1", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "1", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "42", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "42", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "42", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "42", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "42", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "42", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "42", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "42", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "42", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "42", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "42", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "42", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "42", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "42", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "-1", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "-1", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "-1", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "-1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "-1", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "-1", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "-1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "-1", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "-1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "-1", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "-1", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "-1", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "-1", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "-1", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "123456789", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "123456789", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "123456789", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "123456789", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "123456789", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "123456789", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "123456789", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "123456789", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "123456789", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "123456789", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "123456789", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "123456789", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "123456789", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "123456789", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 7}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 3}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 1}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "0", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 5}, + {"clusterUnit": 123456789, "periodIndex": "1", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "2", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "5", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "9", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "10", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "11", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 8}, + {"clusterUnit": 123456789, "periodIndex": "23", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "100", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 2}, + {"clusterUnit": 123456789, "periodIndex": "-1", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 4}, + {"clusterUnit": 123456789, "periodIndex": "-2", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 0}, + {"clusterUnit": 123456789, "periodIndex": "-11", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 9}, + {"clusterUnit": 123456789, "periodIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 6}, + {"clusterUnit": 123456789, "periodIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 10, "expectedVariant": 2} + ], + "fisherYatesPermutation": [ + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "42", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "42", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "42", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "-1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "-1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "-1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "0", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "0", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "0", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "0", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "0", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "0", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "0", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "0", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "1", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "1", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "1", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "1", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "1", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "1", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "1", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "42", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "42", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "42", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "42", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "42", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "42", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "42", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "42", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "-1", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "-1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "-1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "-1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "-1", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "-1", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "-1", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "-1", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "0", "armCount": 10, "expectedPermutation": [0, 3, 7, 5, 8, 2, 6, 4, 1, 9]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "0", "armCount": 10, "expectedPermutation": [6, 0, 3, 8, 9, 7, 2, 4, 5, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "0", "armCount": 10, "expectedPermutation": [3, 0, 4, 8, 1, 6, 9, 2, 7, 5]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "0", "armCount": 10, "expectedPermutation": [0, 2, 7, 9, 1, 6, 4, 5, 3, 8]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "0", "armCount": 10, "expectedPermutation": [6, 9, 8, 3, 4, 7, 2, 5, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "0", "armCount": 10, "expectedPermutation": [1, 7, 8, 3, 9, 5, 0, 4, 6, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "0", "armCount": 10, "expectedPermutation": [8, 9, 3, 6, 4, 1, 5, 0, 2, 7]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "0", "armCount": 10, "expectedPermutation": [6, 4, 3, 1, 0, 7, 8, 9, 5, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "1", "armCount": 10, "expectedPermutation": [9, 4, 3, 5, 8, 0, 2, 6, 7, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "1", "armCount": 10, "expectedPermutation": [3, 8, 4, 0, 1, 7, 5, 6, 2, 9]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "1", "armCount": 10, "expectedPermutation": [4, 1, 5, 3, 6, 7, 0, 9, 2, 8]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "1", "armCount": 10, "expectedPermutation": [7, 0, 1, 5, 2, 9, 8, 6, 4, 3]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "1", "armCount": 10, "expectedPermutation": [9, 1, 7, 3, 4, 5, 2, 6, 8, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "1", "armCount": 10, "expectedPermutation": [0, 5, 7, 2, 6, 1, 9, 4, 8, 3]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "1", "armCount": 10, "expectedPermutation": [2, 4, 0, 7, 5, 1, 3, 8, 9, 6]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "1", "armCount": 10, "expectedPermutation": [6, 2, 5, 3, 4, 1, 7, 8, 9, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "42", "armCount": 10, "expectedPermutation": [3, 7, 2, 9, 5, 8, 0, 1, 4, 6]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "42", "armCount": 10, "expectedPermutation": [0, 8, 1, 6, 3, 4, 5, 9, 7, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "42", "armCount": 10, "expectedPermutation": [1, 3, 2, 0, 7, 6, 8, 4, 9, 5]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "42", "armCount": 10, "expectedPermutation": [5, 7, 0, 6, 1, 4, 3, 8, 2, 9]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "42", "armCount": 10, "expectedPermutation": [6, 5, 2, 0, 1, 3, 4, 9, 8, 7]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "42", "armCount": 10, "expectedPermutation": [0, 6, 9, 1, 4, 2, 3, 8, 7, 5]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "42", "armCount": 10, "expectedPermutation": [8, 1, 3, 6, 5, 0, 4, 9, 7, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "42", "armCount": 10, "expectedPermutation": [6, 8, 3, 5, 7, 4, 2, 0, 1, 9]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "-1", "armCount": 10, "expectedPermutation": [1, 5, 7, 0, 9, 4, 2, 3, 6, 8]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "-1", "armCount": 10, "expectedPermutation": [6, 4, 9, 8, 0, 3, 5, 1, 2, 7]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "-1", "armCount": 10, "expectedPermutation": [4, 0, 5, 8, 9, 3, 7, 6, 1, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "-1", "armCount": 10, "expectedPermutation": [6, 5, 9, 1, 0, 8, 2, 4, 7, 3]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "-1", "armCount": 10, "expectedPermutation": [6, 7, 2, 5, 8, 4, 1, 0, 3, 9]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "-1", "armCount": 10, "expectedPermutation": [0, 5, 6, 3, 1, 7, 8, 4, 2, 9]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "-1", "armCount": 10, "expectedPermutation": [2, 5, 4, 8, 0, 9, 7, 6, 3, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "-1", "armCount": 10, "expectedPermutation": [9, 8, 6, 3, 1, 7, 2, 0, 4, 5]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "123456789", "armCount": 10, "expectedPermutation": [3, 6, 5, 1, 2, 9, 8, 0, 4, 7]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "123456789", "armCount": 10, "expectedPermutation": [6, 2, 1, 7, 3, 8, 0, 4, 5, 9]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "123456789", "armCount": 10, "expectedPermutation": [8, 1, 2, 5, 7, 9, 0, 6, 4, 3]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "123456789", "armCount": 10, "expectedPermutation": [8, 3, 9, 0, 7, 1, 6, 5, 4, 2]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "123456789", "armCount": 10, "expectedPermutation": [1, 9, 3, 7, 4, 8, 0, 5, 2, 6]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "123456789", "armCount": 10, "expectedPermutation": [1, 4, 8, 9, 2, 3, 7, 5, 6, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "123456789", "armCount": 10, "expectedPermutation": [1, 0, 7, 3, 4, 6, 5, 2, 8, 9]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "123456789", "armCount": 10, "expectedPermutation": [6, 4, 3, 7, 1, 9, 8, 2, 0, 5]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [3, 9, 6, 8, 4, 7, 2, 5, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [3, 1, 7, 8, 9, 0, 2, 4, 5, 6]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [7, 6, 8, 3, 2, 5, 4, 1, 9, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [8, 3, 7, 6, 2, 9, 5, 4, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [4, 9, 2, 7, 1, 6, 0, 8, 3, 5]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [4, 9, 3, 5, 8, 6, 7, 2, 0, 1]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [0, 9, 2, 7, 1, 3, 6, 8, 4, 5]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [9, 5, 1, 0, 6, 7, 2, 4, 8, 3]}, + {"clusterUnit": "market_1", "cycleIndex": "0", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [8, 1, 6, 3, 5, 7, 0, 4, 2, 9]}, + {"clusterUnit": "market_1", "cycleIndex": "1", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [0, 5, 6, 3, 2, 7, 4, 9, 1, 8]}, + {"clusterUnit": "market_1", "cycleIndex": "2", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [7, 9, 5, 3, 4, 6, 8, 2, 1, 0]}, + {"clusterUnit": "market_1", "cycleIndex": "-1", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [0, 7, 5, 3, 6, 2, 4, 9, 1, 8]}, + {"clusterUnit": "market_1", "cycleIndex": "-2", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [2, 5, 3, 7, 9, 1, 4, 0, 8, 6]}, + {"clusterUnit": "market_1", "cycleIndex": "100", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [6, 1, 2, 9, 5, 0, 8, 3, 7, 4]}, + {"clusterUnit": "market_1", "cycleIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [7, 5, 6, 9, 4, 8, 2, 0, 1, 3]}, + {"clusterUnit": "market_1", "cycleIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [5, 7, 8, 6, 3, 2, 0, 4, 1, 9]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "42", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "42", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "42", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "-1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "-1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "-1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "-1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "0", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "0", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "0", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "0", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "0", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "0", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "0", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "0", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "1", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "1", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "1", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "1", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "1", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "42", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "42", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "42", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "42", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "42", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "42", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "42", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "42", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "-1", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "-1", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "-1", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "-1", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "-1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "-1", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "-1", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "-1", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "123456789", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "0", "armCount": 10, "expectedPermutation": [4, 6, 2, 7, 5, 8, 9, 0, 1, 3]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "0", "armCount": 10, "expectedPermutation": [1, 2, 5, 9, 8, 6, 0, 3, 4, 7]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "0", "armCount": 10, "expectedPermutation": [8, 4, 6, 3, 1, 2, 0, 5, 9, 7]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "0", "armCount": 10, "expectedPermutation": [5, 2, 3, 0, 4, 6, 7, 1, 9, 8]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "0", "armCount": 10, "expectedPermutation": [9, 7, 8, 2, 1, 6, 0, 3, 4, 5]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "0", "armCount": 10, "expectedPermutation": [8, 6, 9, 3, 4, 2, 0, 1, 7, 5]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "0", "armCount": 10, "expectedPermutation": [0, 9, 5, 4, 1, 7, 8, 6, 2, 3]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "0", "armCount": 10, "expectedPermutation": [5, 8, 0, 2, 9, 7, 6, 3, 4, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "1", "armCount": 10, "expectedPermutation": [4, 2, 5, 9, 0, 7, 8, 1, 3, 6]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "1", "armCount": 10, "expectedPermutation": [1, 7, 9, 2, 6, 0, 4, 5, 3, 8]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "1", "armCount": 10, "expectedPermutation": [2, 8, 7, 5, 6, 9, 3, 4, 0, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "1", "armCount": 10, "expectedPermutation": [2, 3, 4, 9, 6, 7, 8, 5, 1, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "1", "armCount": 10, "expectedPermutation": [2, 3, 8, 5, 9, 1, 7, 6, 4, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "1", "armCount": 10, "expectedPermutation": [4, 6, 2, 3, 0, 5, 9, 1, 8, 7]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "1", "armCount": 10, "expectedPermutation": [8, 6, 1, 2, 5, 9, 4, 0, 3, 7]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "1", "armCount": 10, "expectedPermutation": [7, 5, 0, 9, 1, 2, 6, 4, 3, 8]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "42", "armCount": 10, "expectedPermutation": [9, 2, 3, 8, 0, 6, 5, 1, 7, 4]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "42", "armCount": 10, "expectedPermutation": [0, 9, 7, 3, 5, 6, 2, 4, 1, 8]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "42", "armCount": 10, "expectedPermutation": [4, 0, 3, 8, 1, 6, 9, 2, 7, 5]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "42", "armCount": 10, "expectedPermutation": [5, 9, 3, 0, 4, 8, 6, 7, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "42", "armCount": 10, "expectedPermutation": [7, 8, 0, 9, 6, 2, 5, 4, 3, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "42", "armCount": 10, "expectedPermutation": [1, 3, 5, 8, 6, 4, 0, 9, 7, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "42", "armCount": 10, "expectedPermutation": [3, 1, 0, 8, 2, 7, 6, 4, 5, 9]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "42", "armCount": 10, "expectedPermutation": [0, 9, 6, 5, 2, 1, 7, 3, 8, 4]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "-1", "armCount": 10, "expectedPermutation": [0, 6, 9, 7, 2, 8, 3, 4, 5, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "-1", "armCount": 10, "expectedPermutation": [1, 5, 2, 9, 3, 8, 6, 7, 4, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "-1", "armCount": 10, "expectedPermutation": [8, 7, 3, 1, 2, 9, 6, 4, 5, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "-1", "armCount": 10, "expectedPermutation": [3, 0, 6, 1, 9, 2, 5, 8, 7, 4]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "-1", "armCount": 10, "expectedPermutation": [9, 5, 1, 4, 3, 7, 6, 0, 2, 8]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "-1", "armCount": 10, "expectedPermutation": [5, 6, 9, 7, 8, 1, 0, 4, 2, 3]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "-1", "armCount": 10, "expectedPermutation": [0, 8, 2, 4, 6, 3, 5, 1, 9, 7]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "-1", "armCount": 10, "expectedPermutation": [4, 3, 8, 6, 0, 2, 5, 9, 7, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "123456789", "armCount": 10, "expectedPermutation": [4, 1, 2, 7, 0, 6, 9, 8, 3, 5]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "123456789", "armCount": 10, "expectedPermutation": [4, 5, 3, 9, 1, 7, 6, 0, 8, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "123456789", "armCount": 10, "expectedPermutation": [7, 8, 6, 9, 0, 3, 5, 4, 2, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "123456789", "armCount": 10, "expectedPermutation": [6, 8, 2, 5, 7, 4, 9, 1, 3, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "123456789", "armCount": 10, "expectedPermutation": [6, 5, 7, 8, 0, 2, 3, 1, 9, 4]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "123456789", "armCount": 10, "expectedPermutation": [3, 6, 4, 5, 0, 7, 9, 8, 1, 2]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "123456789", "armCount": 10, "expectedPermutation": [8, 6, 3, 4, 7, 9, 5, 1, 2, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "123456789", "armCount": 10, "expectedPermutation": [0, 1, 8, 9, 2, 6, 4, 5, 3, 7]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [0, 5, 6, 4, 2, 1, 9, 3, 7, 8]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [4, 2, 3, 8, 1, 5, 0, 9, 7, 6]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [7, 3, 2, 1, 5, 9, 8, 0, 4, 6]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [4, 2, 5, 7, 9, 3, 8, 1, 0, 6]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [5, 4, 1, 8, 9, 2, 7, 0, 6, 3]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [2, 9, 6, 4, 8, 0, 1, 5, 3, 7]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [9, 5, 8, 2, 7, 3, 1, 6, 4, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [7, 9, 6, 0, 2, 5, 1, 8, 3, 4]}, + {"clusterUnit": "market_2", "cycleIndex": "0", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [2, 0, 5, 9, 1, 7, 8, 3, 4, 6]}, + {"clusterUnit": "market_2", "cycleIndex": "1", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [3, 7, 9, 8, 4, 2, 1, 6, 5, 0]}, + {"clusterUnit": "market_2", "cycleIndex": "2", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [7, 6, 0, 2, 5, 9, 1, 3, 4, 8]}, + {"clusterUnit": "market_2", "cycleIndex": "-1", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [9, 0, 6, 4, 3, 7, 5, 2, 8, 1]}, + {"clusterUnit": "market_2", "cycleIndex": "-2", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [6, 1, 9, 4, 8, 5, 3, 2, 0, 7]}, + {"clusterUnit": "market_2", "cycleIndex": "100", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [5, 9, 2, 1, 0, 4, 7, 6, 3, 8]}, + {"clusterUnit": "market_2", "cycleIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [0, 3, 7, 6, 4, 5, 2, 8, 1, 9]}, + {"clusterUnit": "market_2", "cycleIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [8, 0, 5, 9, 7, 4, 6, 3, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "0", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "0", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "42", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "42", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "42", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "-1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "-1", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "-1", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "123456789", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "123456789", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 2, "expectedPermutation": [0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "0", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "0", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "0", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "0", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "0", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "0", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "0", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "0", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "1", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "1", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "1", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "1", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "1", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "42", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "42", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "42", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "42", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "42", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "42", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "42", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "42", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "-1", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "-1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "-1", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "-1", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "-1", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "-1", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "-1", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "-1", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "123456789", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "123456789", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "123456789", "armCount": 3, "expectedPermutation": [1, 2, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 1, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [0, 2, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 0, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 3, "expectedPermutation": [2, 1, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "0", "armCount": 10, "expectedPermutation": [9, 0, 1, 7, 3, 4, 5, 8, 2, 6]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "0", "armCount": 10, "expectedPermutation": [4, 9, 7, 6, 1, 5, 8, 2, 0, 3]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "0", "armCount": 10, "expectedPermutation": [4, 1, 5, 8, 9, 6, 2, 3, 0, 7]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "0", "armCount": 10, "expectedPermutation": [5, 0, 1, 6, 7, 3, 9, 8, 2, 4]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "0", "armCount": 10, "expectedPermutation": [5, 2, 9, 4, 1, 0, 8, 6, 3, 7]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "0", "armCount": 10, "expectedPermutation": [7, 5, 8, 3, 0, 9, 2, 6, 1, 4]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "0", "armCount": 10, "expectedPermutation": [0, 5, 7, 9, 3, 2, 4, 1, 8, 6]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "0", "armCount": 10, "expectedPermutation": [9, 5, 6, 3, 1, 2, 8, 7, 4, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "1", "armCount": 10, "expectedPermutation": [9, 7, 4, 8, 1, 0, 5, 3, 6, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "1", "armCount": 10, "expectedPermutation": [9, 3, 7, 1, 8, 5, 0, 4, 6, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "1", "armCount": 10, "expectedPermutation": [9, 5, 1, 8, 0, 3, 4, 6, 7, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "1", "armCount": 10, "expectedPermutation": [4, 9, 3, 1, 6, 8, 7, 2, 5, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "1", "armCount": 10, "expectedPermutation": [1, 0, 6, 9, 8, 5, 2, 7, 3, 4]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "1", "armCount": 10, "expectedPermutation": [0, 7, 8, 3, 1, 5, 4, 9, 6, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "1", "armCount": 10, "expectedPermutation": [1, 9, 5, 4, 8, 2, 0, 7, 6, 3]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "1", "armCount": 10, "expectedPermutation": [3, 4, 2, 9, 0, 5, 1, 7, 6, 8]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "42", "armCount": 10, "expectedPermutation": [6, 1, 9, 7, 5, 8, 3, 4, 2, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "42", "armCount": 10, "expectedPermutation": [2, 8, 3, 0, 1, 7, 9, 6, 4, 5]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "42", "armCount": 10, "expectedPermutation": [5, 1, 3, 2, 0, 6, 9, 8, 7, 4]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "42", "armCount": 10, "expectedPermutation": [2, 7, 6, 9, 5, 0, 1, 8, 3, 4]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "42", "armCount": 10, "expectedPermutation": [8, 5, 4, 3, 2, 1, 0, 7, 9, 6]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "42", "armCount": 10, "expectedPermutation": [4, 6, 5, 9, 0, 2, 7, 3, 8, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "42", "armCount": 10, "expectedPermutation": [1, 9, 4, 0, 6, 8, 7, 3, 2, 5]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "42", "armCount": 10, "expectedPermutation": [8, 1, 4, 7, 0, 9, 3, 2, 6, 5]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "-1", "armCount": 10, "expectedPermutation": [8, 4, 5, 2, 3, 0, 9, 7, 6, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "-1", "armCount": 10, "expectedPermutation": [8, 0, 4, 2, 6, 7, 9, 1, 3, 5]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "-1", "armCount": 10, "expectedPermutation": [2, 8, 7, 6, 9, 0, 5, 4, 3, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "-1", "armCount": 10, "expectedPermutation": [7, 3, 4, 8, 5, 6, 9, 1, 0, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "-1", "armCount": 10, "expectedPermutation": [5, 6, 0, 1, 2, 8, 4, 3, 7, 9]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "-1", "armCount": 10, "expectedPermutation": [9, 6, 3, 4, 8, 2, 1, 7, 0, 5]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "-1", "armCount": 10, "expectedPermutation": [4, 2, 0, 5, 1, 3, 8, 9, 6, 7]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "-1", "armCount": 10, "expectedPermutation": [0, 4, 1, 6, 3, 5, 9, 2, 8, 7]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "123456789", "armCount": 10, "expectedPermutation": [9, 0, 2, 7, 5, 4, 3, 1, 8, 6]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "123456789", "armCount": 10, "expectedPermutation": [6, 1, 2, 7, 5, 3, 0, 9, 4, 8]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "123456789", "armCount": 10, "expectedPermutation": [7, 9, 2, 8, 5, 6, 0, 4, 3, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "123456789", "armCount": 10, "expectedPermutation": [5, 2, 8, 4, 0, 9, 1, 7, 6, 3]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "123456789", "armCount": 10, "expectedPermutation": [1, 0, 7, 3, 5, 6, 4, 8, 9, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "123456789", "armCount": 10, "expectedPermutation": [3, 0, 7, 4, 1, 6, 5, 2, 8, 9]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "123456789", "armCount": 10, "expectedPermutation": [9, 1, 3, 5, 6, 4, 7, 0, 8, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "123456789", "armCount": 10, "expectedPermutation": [6, 2, 0, 7, 8, 1, 3, 4, 5, 9]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [9, 0, 8, 2, 7, 5, 3, 6, 4, 1]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [0, 5, 1, 8, 2, 3, 9, 6, 7, 4]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [5, 0, 8, 2, 9, 4, 1, 6, 3, 7]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [5, 4, 8, 6, 1, 9, 7, 2, 0, 3]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [0, 1, 3, 7, 6, 4, 2, 9, 8, 5]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [0, 5, 2, 9, 6, 1, 4, 8, 3, 7]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [9, 8, 5, 1, 3, 0, 6, 4, 7, 2]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "-9223372036854775808", "armCount": 10, "expectedPermutation": [8, 3, 7, 2, 0, 1, 4, 5, 9, 6]}, + {"clusterUnit": 123456789, "cycleIndex": "0", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [5, 6, 8, 1, 7, 9, 4, 2, 3, 0]}, + {"clusterUnit": 123456789, "cycleIndex": "1", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [4, 8, 0, 6, 9, 7, 5, 2, 1, 3]}, + {"clusterUnit": 123456789, "cycleIndex": "2", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [2, 0, 8, 6, 3, 7, 9, 5, 1, 4]}, + {"clusterUnit": 123456789, "cycleIndex": "-1", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [6, 2, 3, 5, 7, 1, 9, 8, 0, 4]}, + {"clusterUnit": 123456789, "cycleIndex": "-2", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [5, 6, 7, 4, 2, 1, 8, 3, 0, 9]}, + {"clusterUnit": 123456789, "cycleIndex": "100", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [4, 9, 1, 7, 2, 5, 0, 6, 3, 8]}, + {"clusterUnit": 123456789, "cycleIndex": "-9223372036854775808", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [3, 4, 1, 2, 8, 0, 5, 9, 6, 7]}, + {"clusterUnit": 123456789, "cycleIndex": "9223372036854775807", "seed": "9223372036854775807", "armCount": 10, "expectedPermutation": [2, 5, 4, 6, 7, 9, 1, 0, 3, 8]} + ] +} diff --git a/spec/fixtures/resources/switchback_context.json b/spec/fixtures/resources/switchback_context.json new file mode 100644 index 00000000..26be6107 --- /dev/null +++ b/spec/fixtures/resources/switchback_context.json @@ -0,0 +1,93 @@ +{ + "experiments":[ + { + "id":1, + "name":"exp_test_switchback", + "iteration":1, + "unitType":"store_id", + "seedHi":3603515, + "seedLo":233373850, + "split":[ + 0.5, + 0.5 + ], + "trafficSeedHi":449867249, + "trafficSeedLo":455443629, + "trafficSplit":[ + 0.0, + 1.0 + ], + "fullOnVariant":0, + "applications":[ + { + "name":"website" + } + ], + "variants":[ + { + "name":"A", + "config":null + }, + { + "name":"B", + "config":"{\"banner.border\":1}" + } + ], + "audience":null, + "randomizationType":"switchback", + "switchbackClusters":{ + "store_id":"store/key", + "device_id":"geo/city" + }, + "switchbackClusterValues":["porto","lisbon"], + "switchbackClusterUnitType":"store_id", + "switchbackStartAt":1767225600000, + "switchbackPeriodMs":3600000, + "switchbackCarryoverDurationMs":900000, + "switchbackBurnInDurationMs":600000, + "switchbackBurnOutDurationMs":0, + "switchbackDesignType":"balanced_block", + "switchbackEstimand":"global_average_treatment_effect", + "switchbackClusterCount":50, + "switchbackClusterAttribute":"geo/city", + "switchbackFutureField":{"nested":[1,2,3]} + }, + { + "id":2, + "name":"exp_test_unit", + "iteration":1, + "unitType":"session_id", + "seedHi":55006150, + "seedLo":47189152, + "split":[ + 0.5, + 0.5 + ], + "trafficSeedHi":705671872, + "trafficSeedLo":212903484, + "trafficSplit":[ + 0.0, + 1.0 + ], + "fullOnVariant":0, + "applications":[ + { + "name":"website" + } + ], + "variants":[ + { + "name":"A", + "config":null + }, + { + "name":"B", + "config":null + } + ], + "audience":null, + "randomizationType":"unit", + "switchbackStartAt":null + } + ] +} diff --git a/spec/switchback_internals_spec.rb b/spec/switchback_internals_spec.rb new file mode 100644 index 00000000..44f2744a --- /dev/null +++ b/spec/switchback_internals_spec.rb @@ -0,0 +1,276 @@ +# frozen_string_literal: true + +require "json" +require "absmartly/switchback" +require "switchback_support" + +# Ports of java-sdk SwitchbackAssignerGoldenVectorsTest, SwitchbackAttributePathTest and +# SwitchbackServingTest (core-api/src/test/java/com/absmartly/sdk/internal). +module SwitchbackInternalsSpec + Assigner = Absmartly::Switchback::Assigner + AttributePath = Absmartly::Switchback::AttributePath + ClusterKeys = Absmartly::Switchback::ClusterKeys + Serving = Absmartly::Switchback::Serving + LONG_MIN = -(2**63) + LONG_MAX = (2**63) - 1 + + def self.fixture(name) + File.read(File.join(__dir__, "fixtures", "resources", "switchback", name)) + end + + # Fixture copied byte-for-byte from absmartly/abs 9bd2b5ca35 + # lib/utils/src/test/resources/switchback/golden-vectors.json (git blob b314abeb9e97), + # as java-sdk vendors it. + RSpec.describe "Switchback assigner" do + let(:vectors) { JSON.parse(SwitchbackInternalsSpec.fixture("golden-vectors.json")) } + + # The platform hashes a numeric cluster unit as its decimal text; strings pass through. + def cluster_unit(value) + expect(value).to be_a(String).or be_a(Integer) + value.to_s + end + + # 64-bit fields are decimal strings; a number would mean a lossy encoding. + def exact_long(value) + expect(value).to be_a(String) + Integer(value, 10) + end + + it "is the byte-identical platform fixture" do + bytes = SwitchbackInternalsSpec.fixture("golden-vectors.json").b + expect(Digest::SHA1.hexdigest("blob #{bytes.bytesize}\0#{bytes}")).to start_with("b314abeb9e97") + end + + it "matches every assignSwitchback golden vector" do + cases = vectors["assignSwitchback"] + expect(cases.length).to eq(882) + arm_counts = [] + boundary = 0 + cases.each do |c| + period = exact_long(c["periodIndex"]) + seed = exact_long(c["seed"]) + arm_counts << c["armCount"] + boundary += 1 if [LONG_MIN, LONG_MAX].include?(period) || [LONG_MIN, LONG_MAX].include?(seed) + expect(Assigner.assign(cluster_unit(c["clusterUnit"]), period, seed, c["armCount"])) + .to eq(c["expectedVariant"]), c.to_s + end + expect(arm_counts.uniq).to include(2, 3, 10) + expect(boundary).to be > 0 + end + + it "matches every fisherYatesPermutation golden vector" do + cases = vectors["fisherYatesPermutation"] + expect(cases.length).to eq(504) + cases.each do |c| + base = Assigner.base_hash(cluster_unit(c["clusterUnit"]), exact_long(c["cycleIndex"]), exact_long(c["seed"])) + expect(Assigner.fisher_yates_permutation(c["armCount"], base)).to eq(c["expectedPermutation"]), c.to_s + end + end + + it "covers every arm exactly once per cycle" do + [2, 3, 10].each do |arms| + (-3...20).each do |cycle| + variants = (0...arms).map { |slot| Assigner.assign("store_42", cycle * arms + slot, 0x1234_5678_9abc, arms) } + expect(variants.sort).to eq((0...arms).to_a) + end + end + end + + it "rejects fewer than two arms" do + expect { Assigner.assign("u", 0, 0, 1) }.to raise_error(ArgumentError) + expect { Assigner.fisher_yates_permutation(0, 0) }.to raise_error(ArgumentError) + end + + # The cycle is Java's floorDiv(period, arms) and the slot its floorMod, including negative + # periods and the 64-bit bounds: every period of one cycle draws from that cycle's permutation. + it "floors the cycle and slot of negative and boundary periods" do + # [period, arms, floorDiv, floorMod], written out rather than computed. + [[-1, 2, -1, 1], [-4, 3, -2, 2], [-11, 10, -2, 9], [LONG_MIN, 3, -3_074_457_345_618_258_603, 1], + [LONG_MAX, 10, 922_337_203_685_477_580, 7]].each do |period, arms, cycle, slot| + permutation = Assigner.fisher_yates_permutation(arms, Assigner.base_hash("store-42", cycle, 12_345)) + expect(Assigner.assign("store-42", period, 12_345, arms)).to eq(permutation[slot]), [period, arms].inspect + end + # Truncating toward zero would draw from cycle 0 instead of cycle -1. + expect(Assigner.assign("store-42", -1, 12_345, 2)).to eq(0) + expect(Assigner.fisher_yates_permutation(2, Assigner.base_hash("store-42", 0, 12_345))[1]).to eq(1) + end + end + + # Fixture copied byte-for-byte from absmartly/abs 9bd2b5ca35 + # collector/src/test/resources/switchback/attribute-path-cases.json (git blob 7b1d3fed5985), + # as java-sdk vendors it. + RSpec.describe "Switchback attribute paths" do + def parse(path) + AttributePath.parse_supported(path) + end + + it "is the byte-identical platform fixture" do + bytes = SwitchbackInternalsSpec.fixture("attribute-path-cases.json").b + expect(Digest::SHA1.hexdigest("blob #{bytes.bytesize}\0#{bytes}")).to start_with("7b1d3fed5985") + end + + it "matches every path case" do + fixture = JSON.parse(SwitchbackInternalsSpec.fixture("attribute-path-cases.json")) + cases = fixture["cases"] + expect(cases.length).to eq(7) + cases.each do |c| + path = parse(c["path"]) + if c["supported"] + expect(path).not_to be_nil, c.to_s + expect(path.resolve(fixture["attributes"])).to eq(c["value"]), c.to_s + else + expect(path).to be_nil, c.to_s + end + end + end + + it "reads quoted segments as literal keys" do + attributes = { "geo" => { "0" => "zero", "a/b" => "slash" } } + expect(parse("geo/'0'").resolve(attributes)).to eq("zero") + expect(parse("geo/\"a/b\"").resolve(attributes)).to eq("slash") + end + + # An unterminated quote anywhere, or a '.' anywhere, quoted or not. + it "rejects malformed paths" do + ["geo/'0", "'geo", "\"geo/city", "geo/\"", "geo.city", "geo/a.b", "a./b", ".", "items/0.5/city", + "'geo.city'", "\"geo.city\"", "geo/'a.b'"].each do |path| + expect(parse(path)).to be_nil, path + end + end + + it "collapses separators" do + attributes = { "geo" => { "city" => "Porto" } } + expect(parse("/geo//city/").resolve(attributes)).to eq("Porto") + expect(parse("geo").resolve(attributes)).to eq(attributes["geo"]) + end + + it "rejects unsupported paths" do + [nil, "", "/", "//", "0/city", "items/0", "items/0/1/city", "items/-1/city", "'", 7, :geo].each do |path| + expect(parse(path)).to be_nil, path.inspect + end + end + + it "reads lists only with index segments and maps only with key segments" do + attributes = { "items" => [{ "city" => "Lisbon" }], "geo" => { "0" => { "city" => "zero" } }, + "name" => "scalar" } + expect(parse("geo/0/city").resolve(attributes)).to be_nil + expect(parse("items/1/city").resolve(attributes)).to be_nil + expect(parse("name/x").resolve(attributes)).to be_nil + expect(parse("missing/x").resolve(attributes)).to be_nil + expect(parse("items/-0/city").resolve(attributes)).to eq("Lisbon") + end + + it "gives no key for cyclic or too-deep values" do + path = parse("geo/city") + + cyclic = { "city" => "Porto" } + cyclic["self"] = cyclic + expect(path.resolve_attribute(cyclic)).to be_nil + + outer = { "city" => "Porto" } + outer["items"] = [[outer]] + expect(path.resolve_attribute(outer)).to be_nil + + # 65 nested maps: one past the depth bound. + deep = { "leaf" => "x" } + 64.times { deep = { "city" => "Porto", "next" => deep } } + expect(path.resolve_attribute(deep)).to be_nil + expect(path.resolve_attribute(deep["next"])).to eq("Porto") + + # A value reached twice through siblings is not a cycle. + shared = { "a" => "b" } + expect(path.resolve_attribute({ "city" => "Porto", "x" => shared, "y" => shared })).to eq("Porto") + end + + # Values are read through their JSON encoding, as the Collector reads the published + # attribute: Symbol keys and values become strings, a Float stays a Float. + it "reads values through their JSON encoding" do + path = parse("geo/city") + expect(path.resolve_attribute({ geo: :x, city: :Porto })).to eq("Porto") + expect(path.resolve_attribute({ "city" => 3.0 })).to eq(3.0) + expect(path.resolve_attribute({ "city" => 2**70 })).to eq(2**70) + expect(parse("geo").resolve_attribute(:lisboa)).to eq("lisboa") + expect(parse("geo").resolve_attribute(Float::NAN)).to be_nil + end + + it "parses index segments as Guava Ints.tryParse does" do + expect(%w[0 -0 007 2147483647 -2147483648].map { |s| AttributePath.try_parse_int(s) }) + .to eq([0, 0, 7, 2_147_483_647, -2_147_483_648]) + ["", "-", "+1", "1a", " 1", "2147483648", "-2147483649", "99999999999999999999", "٠", "1.0", "1\n"] + .each { |s| expect(AttributePath.try_parse_int(s)).to be_nil, s.inspect } + end + end + + # The owner's cluster-value rule: a non-empty String as-is, a whole-number Integer as its + # base-10 text; every Float (3.0 included), boolean, object, array, "" and nil give none. + RSpec.describe "Switchback cluster keys" do + it "keys strings as-is and integers by their decimal text" do + expect(ClusterKeys.normalize("s-1")).to eq("s-1") + expect(ClusterKeys.normalize(17)).to eq("17") + expect(ClusterKeys.normalize(-5)).to eq("-5") + expect(ClusterKeys.normalize(2**64)).to eq("18446744073709551616") + end + + it "gives no key for anything else" do + values = [nil, "", true, false, 3.0, 1.5, Float::INFINITY, Rational(3, 1), :sym, { "a" => 1 }, ["a"]] + # A bundled gem, not in the Gemfile, from Ruby 3.4. + values << BigDecimal("3") if SwitchbackSpecSupport.big_decimal? + values.each { |value| expect(ClusterKeys.normalize(value)).to be_nil, value.inspect } + end + end + + RSpec.describe "Switchback serving" do + def resolve(types, paths, allowed, units, attributes) + Serving.resolve(types, paths.map { |p| AttributePath.parse_supported(p) }, allowed, units) do |path| + path.resolve(attributes) + end + end + + # The declared source order decides, not the order of the units. + it "lets the source order decide whatever the unit order" do + serving = resolve(%w[session_id user_id], %w[session_store user_store], nil, + { "user_id" => "u1", "session_id" => "x1" }, + { "session_store" => "s-1", "user_store" => "s-1" }) + expect([serving.status, serving.unit_type, serving.cluster_key]).to eq([Serving::ELIGIBLE, "session_id", "s-1"]) + end + + it "skips a unit without a value, and a disagreement is ineligible under the first unit" do + skipped = resolve(%w[session_id user_id], %w[session_store user_store], nil, + { "session_id" => "x1", "user_id" => "u1" }, { "user_store" => "s-2" }) + expect([skipped.status, skipped.unit_type, skipped.cluster_key]).to eq([Serving::ELIGIBLE, "user_id", "s-2"]) + + disagree = resolve(%w[session_id user_id], %w[session_store user_store], nil, + { "session_id" => "x1", "user_id" => "u1" }, + { "session_store" => "s-1", "user_store" => "s-2" }) + expect([disagree.status, disagree.unit_type, disagree.cluster_key]).to eq([Serving::INELIGIBLE, "session_id", nil]) + end + + it "is absent without a linked unit" do + expect(resolve(%w[session_id], %w[session_store], nil, { "user_id" => "u" }, {}).status).to eq(Serving::ABSENT) + end + + it "admits every value with a nil or empty allow-list" do + expect(Serving.allowed?(nil, "a")).to be(true) + expect(Serving.allowed?([], "a")).to be(true) + expect(Serving.allowed?(%w[b], "a")).to be(false) + expect(Serving.allowed?(%w[b a], "a")).to be(true) + expect(Serving.allowed?([17], "17")).to be(true) + expect(Serving.allowed?("a", "a")).to be(false) + # Scalars match their JSON text, as Jackson coerces them into java-sdk's String[]. + expect(Serving.allowed?([true], "true")).to be(true) + expect(Serving.allowed?([1.5], "1.5")).to be(true) + expect(Serving.allowed?([nil, { "a" => "a" }, ["a"], Float::NAN], "a")).to be(false) + expect(Serving.allowed?([{ "a" => "a" }], '{"a"=>"a"}')).to be(false) + expect(Serving.allowed?([["a"]], '["a"]')).to be(false) + end + + it "keeps the declared cluster order" do + clusters = { "user_id" => "u", "session_id" => "s", "device_id" => "d" } + expect(Serving.source_types(clusters)).to eq(%w[user_id session_id device_id]) + expect(Serving.source_types({ user_id: "u" })).to eq(%w[user_id]) + expect(Serving.source_types({})).to be_nil + expect(Serving.source_paths({ "user_id" => "u", "session_id" => "'x" })).to be_nil + expect(Serving.source_paths({ "user_id" => nil })).to be_nil + end + end +end diff --git a/spec/switchback_support.rb b/spec/switchback_support.rb new file mode 100644 index 00000000..0d988fda --- /dev/null +++ b/spec/switchback_support.rb @@ -0,0 +1,122 @@ +# frozen_string_literal: true + +require "json" +require "context" +require "context_config" +require "audience_matcher" +require "default_audience_deserializer" +require "default_context_data_deserializer" +require "default_context_event_serializer" +require "default_variable_parser" +require "hashing" +require "variant_assigner" +require "absmartly/switchback" + +# Helpers shared by the switchback context specs (java-sdk SwitchbackTestSupport). +module SwitchbackSpecSupport + HOUR = 3_600_000 + DAY = 24 * HOUR + # 2026-01-01T00:00:00Z, hour aligned. + ANCHOR = 1_767_225_600_000 + + # bigdecimal is a bundled gem, not in the Gemfile, from Ruby 3.4. + def self.big_decimal? + return @big_decimal unless @big_decimal.nil? + + @big_decimal = begin + verbose = $VERBOSE + # Ruby 4.0 warns when a former default gem loads outside the bundle. + $VERBOSE = nil + require "bigdecimal" + true + rescue LoadError + false + ensure + $VERBOSE = verbose + end + end + + # Reads `now`; when next_read is set, the next read returns it once. + class MutableClock + attr_accessor :now, :next_read + + def initialize(now) + @now = now + end + + def call + unless @next_read.nil? + value = @next_read + @next_read = nil + return value + end + @now + end + end + + class Publisher + attr_reader :events + + def initialize + @events = [] + end + + def publish(_context, event) + @events << event + OpenStruct.new(success?: true) + end + end + + class Logger + attr_reader :exposures + + def initialize + @exposures = [] + end + + def handle_event(type, data) + @exposures << data if type == ContextEventLogger::EVENT_TYPE::EXPOSURE + end + end + + # Decodes through the SDK's own deserializer, as a fetched payload is. + def data_of(experiments, holdouts = nil) + payload = { experiments: experiments } + payload[:holdouts] = holdouts unless holdouts.nil? + json = JSON.generate(payload) + DefaultContextDataDeserializer.new.deserialize(json, 0, json.length) + end + + def ready(data) + OpenStruct.new(data_future: data, success?: true) + end + + def build_context(data, units:, attributes: {}, audience_matcher: nil, publisher: Publisher.new, + logger: nil, provider: nil, overrides: {}, custom: {}) + config = ContextConfig.create + config.set_units(units) + config.set_attributes(attributes) unless attributes.empty? + config.set_overrides(overrides) + config.set_custom_assignments(custom) + Context.create(clock, config, ready(data), provider, publisher, logger, DefaultVariableParser.new, + audience_matcher || AudienceMatcher.new(DefaultAudienceDeserializer.new), + application: "website", environment: "production") + end + + def published_exposures(context) + publisher = context.send(:event_handler) + before = publisher.events.length + context.publish + publisher.events[before..].flat_map { |event| event.exposures || [] } + end + + def exposure(id, name, unit, variant, exposed_at, assigned, eligible, overridden = false, full_on = false, + custom = false, audience_mismatch = false, rule_override = false) + Exposure.new(id, name, unit, variant, exposed_at, assigned, eligible, overridden, full_on, custom, + audience_mismatch, rule_override) + end + + def draw(key, period, seed_hi, seed_lo, arms) + Absmartly::Switchback::Assigner.assign(key, period, (seed_hi << 32) | (seed_lo & 0xffffffff), arms) + end +end diff --git a/spec/timestamps_spec.rb b/spec/timestamps_spec.rb new file mode 100644 index 00000000..85e15322 --- /dev/null +++ b/spec/timestamps_spec.rb @@ -0,0 +1,121 @@ +# frozen_string_literal: true + +require "a_b_smartly" +require "a_b_smartly_config" +require "client" +require "context_config" +require "json/context_data" +require "context_data_result" +require "audience_matcher" +require "default_context_data_deserializer" +require "default_variable_parser" +require "switchback_support" +require "default_audience_deserializer" + +# The Collector reads every timestamp as epoch milliseconds, and a context's +# timestamps follow the wall clock, as in the JavaScript and Java SDKs. +RSpec.describe "Context timestamps" do + let(:published) { [] } + let(:client) do + client = instance_double(Client) + allow(client).to receive(:context_data).and_return(Absmartly::ContextDataResult.new(ContextData.new([]))) + allow(client).to receive(:publish) { |event| published << event; OpenStruct.new(success?: true) } + client + end + + def create_context + config = ABSmartlyConfig.create + config.client = client + context_config = ContextConfig.create + context_config.set_unit(:session_id, "abc") + ABSmartly.create(config).create_context(context_config) + end + + it "stamps attributes, goals and the publish in live epoch milliseconds" do + allow(Process).to receive(:clock_gettime).and_call_original + readings = [1_767_225_600_123, 1_767_225_600_456, 1_767_225_601_789] + allow(Process).to receive(:clock_gettime).with(Process::CLOCK_REALTIME, :millisecond) { readings.shift } + context = create_context + context.set_attribute("a", 1) + context.track("goal") + context.publish + + event = published.first + expect(event.attributes.map(&:set_at)).to eq([1_767_225_600_123]) + expect(event.goals.map(&:achieved_at)).to eq([1_767_225_600_456]) + expect(event.published_at).to eq(1_767_225_601_789) + end + + it "stamps in live milliseconds through every context factory" do + allow(Process).to receive(:clock_gettime).and_call_original + readings = (1..9).map { |i| 1_767_225_600_000 + i } + allow(Process).to receive(:clock_gettime).with(Process::CLOCK_REALTIME, :millisecond) { readings.shift } + absmartly = ABSmartly.create(ABSmartlyConfig.create.tap { |config| config.client = client }) + context_config = ContextConfig.create + context_config.set_unit(:session_id, "abc") + contexts = [absmartly.create_context_with(context_config, Absmartly::ContextDataResult.new(ContextData.new([]))), + absmartly.create_context_async(context_config).wait_until_ready(5)] + contexts.each do |context| + context.track("goal") + context.publish + end + + expect(published.map { |event| event.goals.first.achieved_at }).to eq([1_767_225_600_001, 1_767_225_600_003]) + expect(published.map(&:published_at)).to eq([1_767_225_600_002, 1_767_225_600_004]) + end + + # The Collector rejects a batch with an event after publishedAt, so a clock that stepped back + # between an event and the publish must not get the batch rejected; the events keep their stamps. + it "publishes no earlier than its latest event after the clock steps back" do + allow(Process).to receive(:clock_gettime).and_call_original + readings = [1_767_225_600_010, 1_767_225_600_012, 1_767_225_600_005] + allow(Process).to receive(:clock_gettime).with(Process::CLOCK_REALTIME, :millisecond) { readings.shift } + context = create_context + context.track("goal") + context.track("goal") + context.publish + + event = published.first + expect(event.goals.map(&:achieved_at)).to eq([1_767_225_600_010, 1_767_225_600_012]) + expect(event.published_at).to eq(1_767_225_600_012) + end + + it "publishes no earlier than a queued exposure after the clock steps back" do + clock = SwitchbackSpecSupport::MutableClock.new(1_767_225_600_050) + json = File.read(File.join(__dir__, "fixtures", "resources", "context.json")) + data = DefaultContextDataDeserializer.new.deserialize(json, 0, json.length) + config = ContextConfig.create + config.set_unit(:session_id, "e791e240fcd3df7d238cfc285f475e8152fcc0ec") + publisher = SwitchbackSpecSupport::Publisher.new + context = Context.create(clock, config, Absmartly::ContextDataResult.new(data), nil, publisher, nil, + DefaultVariableParser.new, AudienceMatcher.new(DefaultAudienceDeserializer.new)) + context.treatment("exp_test_ab") + clock.now = 1_767_225_600_010 + context.publish + + event = publisher.events.first + expect(event.exposures.map(&:exposed_at)).to eq([1_767_225_600_050]) + expect(event.published_at).to eq(1_767_225_600_050) + end + + it "reads the real wall clock in milliseconds" do + before = (Time.now.to_r * 1000).floor + context = create_context + context.track("goal") + context.publish + after = (Time.now.to_r * 1000).ceil + + expect(published.first.published_at).to be_between(before, after) + expect(published.first.goals.first.achieved_at).to be_between(before, after) + end + + it "keeps a fixed Time as one instant, in milliseconds" do + context = Context.create(Time.at(1_620_000_000, 250, :millisecond), ContextConfig.create, + Absmartly::ContextDataResult.new(ContextData.new([])), nil, nil, nil, nil, + AudienceMatcher.new(DefaultAudienceDeserializer.new)) + context.set_attribute("a", 1) + sleep 0.01 + context.set_attribute("b", 2) + expect(context.send(:attributes).map(&:set_at)).to eq([1_620_000_000_250, 1_620_000_000_250]) + end +end From 7c6fc461d51fd903cca282ab1180831299bab79d Mon Sep 17 00:00:00 2001 From: lux worker Date: Mon, 30 Nov 2026 15:34:50 +0000 Subject: [PATCH 02/15] fix: hash Float and non-UTF-8 unit UIDs as every other SDK does Restores the unit hashing 1.4.0's release prep (d10e62e) reverted to 1.3.0's to_s bytes: a Float UID hashes JavaScript's toFixed(0) text (1.5 -> "2", -0.0 -> "0", -0.4 -> "-0"), and a string in another encoding is transcoded to UTF-8 first (CESU-8 surrogate pairs joined, lone surrogates and invalid bytes -> U+FFFD), as the JavaScript and Java SDKs and the Collector hash them. Integer, BigDecimal, Rational and UTF-8 String UIDs hash as in 1.4.0. Co-Authored-By: Claude Opus 5.5 --- lib/hashing.rb | 33 +++++++++++++++++++++++++++------ spec/compat/v1_3_0_consumer.rb | 6 +++--- spec/context_spec.rb | 9 +++++---- spec/hashing_spec.rb | 13 ++++++++----- spec/parity_spec.rb | 16 +++++++++++----- 5 files changed, 54 insertions(+), 23 deletions(-) diff --git a/lib/hashing.rb b/lib/hashing.rb index e201336e..0e1352fd 100644 --- a/lib/hashing.rb +++ b/lib/hashing.rb @@ -9,19 +9,40 @@ class Hashing # A lone surrogate written as a 3-byte sequence. ENCODED_SURROGATE = /\xED[\xA0-\xBF][\x80-\xBF]/n.freeze - # Hashes the unit's to_s bytes as v1.3.0 does, so every unit keeps its - # bucket: integers from their exact decimal text, floats from Float#to_s and - # strings from their own bytes, whatever their encoding. + # Hashes the unit as the JavaScript and Java SDKs and the Collector do. + # Integers hash as their exact decimal text (as in v1.3.0), so 64-bit IDs + # beyond 2**53 keep distinct buckets; for |n| <= 2**53 this is the same text + # as JavaScript's toFixed(0). Floats are formatted like toFixed(0); other + # numbers (BigDecimal, Rational) hash from to_s, as in v1.3.0. Text is + # hashed as UTF-8, whatever its encoding (see to_utf8). def self.hash_unit(value) - base64_url_no_padding(Digest::MD5.digest(value.to_s.b)) + unit = value.is_a?(Float) ? number_to_fixed0(value) : value + base64_url_no_padding(Digest::MD5.digest(to_utf8(unit).b)) + end + + # The text JavaScript's Number#toFixed(0) produces, which the JS SDK hashes + # for numeric units: rounded half away from zero, "-0" for small negative + # fractions, and exponent notation from 1e21 on. + def self.number_to_fixed0(value) + x = value.to_f + return "NaN" if x.nan? + return (x.positive? ? "Infinity" : "-Infinity") if x.infinite? + + if x.abs >= 1e21 + mantissa, exponent = x.to_s.split("e") + mantissa = mantissa.delete_suffix(".0") + return "#{mantissa}e#{exponent}" + end + + rounded = x.abs.round + x.negative? ? "-#{rounded}" : rounded.to_s end def self.base64_url_no_padding(bytes) [bytes.to_s.b].pack("m0").delete("=").tr("+/", "-_") end - # Returns the UTF-8 form of the unit's Unicode text (hash_unit keeps v1.3.0's - # raw bytes). Characters outside the + # Returns the UTF-8 form of the unit's Unicode text. Characters outside the # BMP become the standard 4-byte sequence and each lone surrogate becomes # U+FFFD, matching the JavaScript SDK's TextEncoder-based encoding. Strings in # another encoding (e.g. UTF-16) are transcoded; binary strings are read as diff --git a/spec/compat/v1_3_0_consumer.rb b/spec/compat/v1_3_0_consumer.rb index f0632358..8dc97de7 100644 --- a/spec/compat/v1_3_0_consumer.rb +++ b/spec/compat/v1_3_0_consumer.rb @@ -139,9 +139,9 @@ def publish(context, event); Exception.new("rejected"); end check.("close on rejected publish does not raise (#{e.class})", false) end -# Float/encoded UIDs hash from to_s bytes as in 1.3.0. -check.("Hashing.hash_unit(1.5)", Hashing.hash_unit(1.5) == Hashing.hash_unit("1.5")) -check.("VariantAssigner float", VariantAssigner.new(125.75).key == VariantAssigner.new("125.75").key) +# 1.5.0 hashes Float UIDs from JavaScript's toFixed(0) text, as every other SDK does. +check.("Hashing.hash_unit(1.5)", Hashing.hash_unit(1.5) == Hashing.hash_unit("2")) +check.("VariantAssigner float", VariantAssigner.new(125.75).key == VariantAssigner.new("126").key) results.each { |n, s| puts "#{s} #{n}" } exit(results.all? { |_, s| s == "ok" } ? 0 : 1) diff --git a/spec/context_spec.rb b/spec/context_spec.rb index b2e3d24e..fbfd4170 100644 --- a/spec/context_spec.rb +++ b/spec/context_spec.rb @@ -431,19 +431,20 @@ def handle_event(event, data) expect(context.get_units[:db_user_id]).to eq(125) end - it "numeric uid assigns and publishes like its to_s text, as in v1.3.0" do + # As the JavaScript SDK hashes a number's toFixed(0) text (1.5.0; 1.4.0 hashed Float#to_s). + it "numeric uid assigns and publishes like its toFixed(0) text, as in the JavaScript SDK" do make = lambda do |uid| config = ContextConfig.create config.set_units(units.merge(session_id: uid)) create_context(data_future_ready, config: config) end numeric = make.call(125.75) - string = make.call("125.75") + string = make.call("126") %w[exp_test_ab exp_test_abc exp_test_fullon].each do |name| expect(numeric.treatment(name)).to eq(string.treatment(name)) end - expect(VariantAssigner.new(125.0).key).to eq(VariantAssigner.new("125.0").key) - expect(VariantAssigner.new(125.75).key).to eq(VariantAssigner.new("125.75").key) + expect(VariantAssigner.new(125.0).key).to eq(VariantAssigner.new("125").key) + expect(VariantAssigner.new(125.75).key).to eq(VariantAssigner.new("126").key) expect(VariantAssigner.new(125).key).to eq(VariantAssigner.new("125").key) end diff --git a/spec/hashing_spec.rb b/spec/hashing_spec.rb index 8630befd..d42923f5 100644 --- a/spec/hashing_spec.rb +++ b/spec/hashing_spec.rb @@ -37,13 +37,16 @@ end end - it "hashes numbers from their to_s text, as in v1.3.0" do + # As the JavaScript SDK hashes a number's toFixed(0) text (1.4.0 hashed Float#to_s). + it "hashes numbers as their value rounded to an integer" do expect(Hashing.hash_unit(12345)).to eq("gnzLDuqKcGxMNKFokfhOew") expect(Hashing.hash_unit(125)).to eq("Pe8YStj0dV_yaYYup3OT3Q") - # v1.3.0 hashed 125.75 as "125.75", -0.4 as "-0.4" and 1.5 as "1.5". - expect(Hashing.hash_unit(125.75)).to eq("DLsKSBpnnh4fCt33hOku3w") - expect(Hashing.hash_unit(-0.4)).to eq("0athA6e68vz3oWEawimSYQ") - expect(Hashing.hash_unit(1.5)).to eq("YAhkcnfERUzs2X0zwGnwyg") + expect(Hashing.hash_unit(125.75)).to eq("BpBZt--EDwx0qBTskje27A") + expect(Hashing.hash_unit(-0.1)).to eq("815ubasUW2p7sFI440lKaw") + expect(Hashing.hash_unit(1e21)).to eq("OKkjo8sn5USSUjdjCUBynw") + { 1.5 => "2", -0.0 => "0", -0.4 => "-0", 2.5 => "3", -2.5 => "-3", 125.0 => "125" }.each do |num, text| + expect(Hashing.hash_unit(num)).to eq(Hashing.hash_unit(text)) + end end it "hashes integers by their exact decimal text, like v1.3.0" do diff --git a/spec/parity_spec.rb b/spec/parity_spec.rb index a713589d..6b61bc8d 100644 --- a/spec/parity_spec.rb +++ b/spec/parity_spec.rb @@ -43,25 +43,31 @@ expect(Hashing.to_utf8(cesu.force_encoding("UTF-8")).bytes).to eq(bytes) end - it "hashes #{value.inspect} in another encoding from its own bytes, as in v1.3.0" do - utf16 = value.encode("UTF-16LE") - expect(Hashing.hash_unit(utf16)).to eq(Hashing.base64_url_no_padding(Digest::MD5.digest(utf16.b))) + # 1.4.0 hashed a non-UTF-8 string's own bytes. + it "hashes #{value.inspect} the same from UTF-16 and from CESU-8 bytes" do + expect(Hashing.hash_unit(value.encode("UTF-16LE"))).to eq(hash) + expect(Hashing.hash_unit(value.encode("UTF-16BE"))).to eq(hash) + cesu = value.encode("UTF-16BE").unpack("n*").map { |u| [u].pack("U") }.join.b + expect(Hashing.hash_unit(cesu.force_encoding("UTF-8"))).to eq(hash) end end it "replaces a lone surrogate in a UTF-16 string with U+FFFD" do utf16 = "ab".encode("UTF-16LE") + [0xD83D].pack("v").force_encoding("UTF-16LE") + "cd".encode("UTF-16LE") expect(Hashing.to_utf8(utf16).bytes).to eq(lone_surrogate_bytes) + expect(Hashing.hash_unit(utf16)).to eq(lone_surrogate_hash) end it "replaces a lone surrogate encoded as UTF-8 bytes with a single U+FFFD" do wtf8 = "ab\xED\xA0\xBDcd".dup.force_encoding("UTF-8") expect(Hashing.to_utf8(wtf8).bytes).to eq(lone_surrogate_bytes) - expect(Hashing.base64_url_no_padding(Digest::MD5.digest(Hashing.to_utf8(wtf8).b))).to eq(lone_surrogate_hash) + expect(Hashing.hash_unit(wtf8)).to eq(lone_surrogate_hash) end it "replaces other invalid bytes with U+FFFD" do - expect(Hashing.to_utf8("a\xFFb".dup.force_encoding("UTF-8")).bytes).to eq([97, 239, 191, 189, 98]) + invalid = "a\xFFb".dup.force_encoding("UTF-8") + expect(Hashing.to_utf8(invalid).bytes).to eq([97, 239, 191, 189, 98]) + expect(Hashing.hash_unit(invalid)).to eq(Hashing.hash_unit("a\u{FFFD}b")) end it "assigns non-BMP units like the JavaScript VariantAssigner" do From 5e0b9697d689b013b8a2cd486793f142e273ef59 Mon Sep 17 00:00:00 2001 From: lux worker Date: Mon, 30 Nov 2026 15:34:50 +0000 Subject: [PATCH 03/15] release: 1.5.0 (version, X-Agent, README, CHANGELOG) Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 17 +++++++++++++++++ Gemfile.lock | 2 +- README.md | 2 +- lib/absmartly/version.rb | 2 +- 4 files changed, 20 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index af5a7b9d..739afefd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,20 @@ +## [1.5.0] - Unreleased + +Adds switchback experiments on top of 1.4.0, without breaking it: every 1.4.0 class, method signature, return value, error and behaviour is kept, and experiments that are not switchbacks are assigned, exposed and published as in 1.4.0. Only the timestamps and two unit-hashing cases change, as each Fixed entry says. + +### Added +- Switchback experiments, served as the Collector and the Java SDK serve them (the R33 cluster-defined contract). An experiment with `randomizationType: "switchback"` lists in `switchbackClusters`, in order, the unit types it is linked to and the attribute path holding each one's cluster value (`/` nests, a quoted segment is a literal key, an integer segment indexes an array). The first linked unit, in declared order, whose attribute gives a value serves the experiment and its exposure; the value is the cluster key, used raw (never hashed): a non-empty String as is, an Integer as its decimal text, while a Float (`3.0` included), boolean, Hash, Array, `""` or `nil` gives none. The variant is the platform's balanced-block draw for the period `floor((now - switchbackStartAt) / switchbackPeriodMs)` and the experiment's 64-bit seed. No value, disagreeing units or a value outside `switchbackClusterValues` give control and no exposure; so do the time before `switchbackStartAt` and an unservable schedule (a start that is not hour aligned, a period of 0 or less, fewer than two arms), where rules, a strict audience and full-on still apply. Overrides, assignment rules (a split rule over the serving unit), strict audiences, full-on, traffic (on the serving unit) and custom assignments apply in the Collector's order; holdouts never apply to a switchback. One exposure is sent per experiment and period while its assignment is unchanged (a custom assignment, override or refresh that rebuilds it within the period, or a clock that returns to a period no longer among the two most recent, sends one more), stamped with the time that chose the period, and the cluster value is read once per period. Changing a unit's cluster attribute mid-period, before its exposure, is not supported: callers set it before the first read, and a change takes effect in the next period. A period keeps a copy of the cluster-source attribute values it read (a String, Array or Hash, to the depth a path reads), so changing a value passed to `set_attribute` in place does not change the cluster it served or the attributes its own exposure request carries; other attributes are not copied, and an in-place change to a key of an identity-compared Hash is not supported. The Collector resolves the serving unit and cluster again from the published units and attributes at `exposedAt`, so a switchback exposure that the batch would credit to another unit or cluster (an attribute changed within the period, a unit set afterwards, a write in the exposure's millisecond, a clock that stepped back) is published in a request of its own, with the units and attributes its period read and its own `exposedAt`; `publish` then sends more than one request. A string cluster value keys by its published UTF-8 text. The new experiment fields (`randomization_type`, `switchback_clusters`, `switchback_cluster_values`, `switchback_start_at`, `switchback_period_ms`, `switchback_carryover_duration_ms`, `switchback_burn_in_duration_ms`, `switchback_burn_out_duration_ms`, `switchback_design_type`, `switchback_estimand`) are optional; payloads without switchbacks assign, expose and publish as in 1.4.0 (one request per `publish`) and read no extra clock to do so. + +### Changed +- Experiments with `randomizationType: "switchback"` are served as switchbacks. 1.4.0 served a switchback that has a `unitType` as an ordinary experiment on that unit (a sticky variant that ignores clusters and periods). Who moves: units in running switchback experiments, which move to their cluster's schedule; their exposures move to the serving unit and to one per period while the assignment is unchanged. +- When `publish` sends a switchback exposure in a request of its own (see Added), the event logger receives one `"publish"` event per request delivered (a failed request logs an `"error"` event instead and stops the call; delivered requests are not sent again), so one `publish` call can log more than one. Payloads without such an exposure still send one request per `publish`, and none when nothing is queued. +- The `X-Agent` header is now `absmartly-ruby-sdk/1.5.0`. + +### Fixed +- Every timestamp the SDK sends (`publishedAt`, `exposedAt`, `setAt`, `achievedAt`) is the current time in epoch milliseconds, as the Collector reads it and the JavaScript and Java SDKs send it. Up to 1.4.0 they were the context's creation time in seconds, so every event looked more than 50 years old and stayed at one instant for the context's life. Contexts made by `ABSmartly#create_context`, `create_context_async` and `create_context_with` read a millisecond clock on every call; a `Time` passed to `Context.create` is still one fixed instant, now in milliseconds, and a callable clock (`-> { millis }`) is read on each call. `publishedAt` is never earlier than an event in its batch, so a wall clock that steps back does not get the batch rejected. Who is affected: every published event changes its timestamps (not its content); collectors, proxies and tests that read or compared those values in seconds see milliseconds. +- Float unit UIDs are hashed from the text JavaScript's `toFixed(0)` gives (`1.5` as `"2"`, `125.75` as `"126"`, `-0.0` as `"0"`, `-0.4` as `"-0"`, `1e21` as `"1e+21"`), as the JavaScript and Java SDKs and the Collector hash them; 1.4.0 hashed `Float#to_s` (`"1.5"`). Integer (exact decimal text, beyond 2**53 too), BigDecimal and Rational UIDs and UTF-8 strings hash as in 1.4.0. Who is affected: units set with a Float UID; they are reassigned once (they may get another variant) and exposed again, and from then on match every other SDK. +- Unit UIDs in another encoding than UTF-8 (e.g. UTF-16) are transcoded to UTF-8 before hashing, a surrogate pair written as CESU-8 bytes is joined, and a lone surrogate or invalid byte becomes U+FFFD, as the JavaScript SDK's `TextEncoder` encodes them; 1.4.0 hashed the string's own bytes. Who is affected: units set with a non-UTF-8 String UID, or a UTF-8 String holding CESU-8 surrogates or invalid bytes; they are reassigned once and exposed again, and from then on match every other SDK. `get_unit` still returns the UID as set. + ## [1.4.0] - 2026-11-17 A non-breaking release of 1.3.0. Code written against 1.3.0 keeps compiling and running: the 1.3.0 classes, method signatures, error types and messages, `close`/`refresh` return values, unit hashing and core extensions are unchanged. Behaviour moves only where the cross-SDK contract or a bug fix requires it; each such entry under Changed says who is affected. diff --git a/Gemfile.lock b/Gemfile.lock index d82861a7..e00ddd63 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - absmartly-sdk (1.4.0) + absmartly-sdk (1.5.0) base64 (~> 0.2) faraday (~> 2.0) faraday-net_http_persistent (~> 2.0) diff --git a/README.md b/README.md index 3db87c10..59336435 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ bundle add absmartly-sdk --version "~> 1.4" If bundler is not being used to manage dependencies, install the gem by executing: ```bash -gem install absmartly-sdk -v 1.4.0 +gem install absmartly-sdk -v 1.5.0 ``` ## Getting Started diff --git a/lib/absmartly/version.rb b/lib/absmartly/version.rb index 6c6f1315..c0c238a9 100644 --- a/lib/absmartly/version.rb +++ b/lib/absmartly/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Absmartly - VERSION = "1.4.0" + VERSION = "1.5.0" end From 1936bd854043281486f103f075d1d75eb2ddbb55 Mon Sep 17 00:00:00 2001 From: lux worker Date: Mon, 30 Nov 2026 17:49:50 +0000 Subject: [PATCH 04/15] perf: keep ordinary reads and context creation faster than 1.4.0 Co-Authored-By: Claude Opus 5.5 --- lib/context.rb | 188 +++++++++++++----------- lib/hashing.rb | 7 +- spec/context_switchback_cluster_spec.rb | 2 +- spec/context_switchback_spec.rb | 17 ++- 4 files changed, 117 insertions(+), 97 deletions(-) diff --git a/lib/context.rb b/lib/context.rb index eee96ec3..44218a33 100644 --- a/lib/context.rb +++ b/lib/context.rb @@ -20,6 +20,8 @@ class Context # Immutable-by-convention snapshot swapped in with a single assignment so # readers see either the complete old or the complete new state. State = Struct.new(:data, :index, :index_variables, :custom_fields) + # A State whose data has a switchback. + SwitchbackSnapshot = Class.new(State) NO_RULES = "" SEAL_FLUSH_PASSES = 2 private_constant :SEAL_FLUSH_PASSES @@ -38,12 +40,19 @@ class EventsQueuedWhileClosing < StandardError; end SWITCHBACK_MAX_ANCHOR_MS = 253_402_300_800_000 # One switchback's cache slots, all created under one generation. SwitchbackEpoch = Struct.new(:generation, :periods) - # Returned by a lookup that found a switchback but was given no clock - # reading: the caller reads the clock, outside the assignment lock, and - # looks it up again with that reading. - NEEDS_CLOCK = Object.new.freeze + # A context's switchback state, created when the first switchback is + # installed, so contexts without switchbacks carry none of it: the epochs by + # experiment name, the last generation handed out, and the queued + # switchback exposures with the slot each was served from (exposures is + # guarded by @queue_mutex, the rest by @assignment_mutex). + SwitchbackState = Struct.new(:epochs, :generation, :exposures) + # A switchback experiment's linked unit types and cluster attribute paths + # (nil on the legacy path), their root attribute names, the cache + # generation and the schedule identity. + SwitchbackEntry = Struct.new(:source_types, :source_paths, :source_roots, :generation, :grid) private_constant :SWITCHBACK, :SWITCHBACK_KEY_SEPARATOR, :SWITCHBACK_RETAINED_PERIODS, - :SWITCHBACK_ANCHOR_ALIGNMENT_MS, :SWITCHBACK_MAX_ANCHOR_MS, :SwitchbackEpoch, :NEEDS_CLOCK + :SWITCHBACK_ANCHOR_ALIGNMENT_MS, :SWITCHBACK_MAX_ANCHOR_MS, :SwitchbackEpoch, :SwitchbackState, + :SwitchbackEntry, :SwitchbackSnapshot attr_reader :pending_count @@ -270,14 +279,9 @@ def treatment(experiment_name) check_ready?(true) # A switchback is resolved, and exposed, at one clock reading. - now = @switchbacks_active ? now_millis : nil + now = @switchbacks ? now_millis : nil while true # rubocop:disable Style/InfiniteLoop -- no block allocation on the read path - assignment = assignment(experiment_name, now, true) - if assignment.equal?(NEEDS_CLOCK) - # A refresh installed the first switchback while this call waited. - now = now_millis - next - end + assignment = assignment(experiment_name, now) # set_unit may evict it between the lookup and the exposure claim: # then it is resolved again, so the variant served is the one exposed. return assignment.variant unless claim_and_queue_exposure(assignment, experiment_name, now) == :evicted @@ -520,7 +524,9 @@ def claim_and_queue_exposure(assignment, experiment_name = nil, now = nil) # Only this assignment is claimed, without holding a lock over the # supplied clock; distinct nested or concurrent exposures can proceed. - exposed_at = assignment.switchback && !now.nil? ? now : now_millis + # A switchback looked up without a reading (see assignment) exposes + # at the reading its slot was resolved at. + exposed_at = assignment.switchback ? now || assignment.serving_read_at : now_millis exposure = nil holdout_exposures = nil @queue_mutex.synchronize do @@ -539,7 +545,7 @@ def claim_and_queue_exposure(assignment, experiment_name = nil, now = nil) # A switchback the Collector records nothing for exposes nothing. unless assignment.switchback_silent exposure = enqueue_exposure(assignment.name, assignment, exposed_at) - (@switchback_exposures ||= {}.compare_by_identity)[exposure] = assignment + (@switchbacks.exposures ||= {}.compare_by_identity)[exposure] = assignment end elsif !assignment.suppressed || assignment.overridden || assignment.rule_override exposure = enqueue_exposure(assignment.name, assignment, exposed_at) @@ -667,7 +673,7 @@ def flush(sealing: false, drop_rejected: false) # grow by appending or are replaced whole, so a handler that # mutates its payload can't change what is removed. sent = [@exposures, exposures.size, @achievements, achievements.size] - switchback_exposures = @switchback_exposures&.dup + switchback_exposures = @switchbacks&.exposures&.dup end end failed_result @@ -749,7 +755,7 @@ def drop_if_failed(sealing) @queue_mutex.synchronize do @exposures = [] @achievements = [] - @switchback_exposures = nil + @switchbacks.exposures = nil unless @switchbacks.nil? @pending_count = 0 end [true, sealing ? nil : @data_failed] @@ -787,12 +793,13 @@ def remove_delivered((exposures, _, achievements, _), events) # ordinary publish returns to the single-request path. Caller holds # @queue_mutex. def forget_switchback_exposures - return if @switchback_exposures.nil? + switchback_exposures = @switchbacks&.exposures + return if switchback_exposures.nil? queued = {}.compare_by_identity @exposures.each { |e| queued[e] = true } - @switchback_exposures.delete_if { |e, _| !queued.key?(e) } - @switchback_exposures = nil if @switchback_exposures.empty? + switchback_exposures.delete_if { |e, _| !queued.key?(e) } + @switchbacks.exposures = nil if switchback_exposures.empty? end # A publish body: hashed units, the attributes and the events. Its @@ -893,13 +900,13 @@ def served_payload(assignment, exposed_at) read = assignment.serving_attributes return [units, read] if served_at?(assignment, exposed_at, units, read) - selected = assignment.switchback_entry.switchback_source_paths.filter_map do |path| + selected = assignment.switchback_entry.switchback.source_paths.filter_map do |path| latest_attribute(path.root_key, assignment.serving_read_at, read) end.to_set # Attributes that are not cluster sources are kept as they are. Of the # cluster-source attributes only those the read selected stay, stamped no # later than exposedAt, so a later value of the same name can't win. - roots = assignment.switchback_entry.switchback_source_paths.map(&:root_key) + roots = assignment.switchback_entry.switchback.source_paths.map(&:root_key) clamped = read.filter_map do |a| if selected.include?(a) a.set_at > exposed_at ? Attribute.new(a.name, a.value, exposed_at) : a @@ -1269,26 +1276,24 @@ def resolve_rule(entry, attrs, unit_pinned_missing, unit_type = entry.data.unit_ # which would reset their exposed flag and expose them again. # now is the caller's clock reading, so a switchback's period, its cluster # attributes and its exposure's exposedAt all agree; without one, the - # clock is read once a switchback is found, unless needs_clock: then - # NEEDS_CLOCK is returned, so the caller exposes at the reading it takes. - def assignment(experiment_name, now = nil, needs_clock = false) - while true # rubocop:disable Style/InfiniteLoop -- no block allocation on the read path - assignment = @assignment_mutex.synchronize { cached_or_new_assignment(experiment_name, @state, now) } - return assignment if needs_clock || !assignment.equal?(NEEDS_CLOCK) - - now = now_millis - end + # clock is read, outside the lock, once a switchback is found (a refresh + # installed the first switchback while the caller read no clock); the + # slot keeps that reading, which its exposure is stamped with. + def assignment(experiment_name, now = nil) + @assignment_mutex.synchronize { cached_or_new_assignment(experiment_name, @state, now) } || + assignment(experiment_name, now_millis) end - # Returns NEEDS_CLOCK for a switchback when now is nil. + # nil for a switchback when now is nil. def cached_or_new_assignment(experiment_name, state, now = nil) exp_key = experiment_name.to_s.to_sym custom = @cassignments[exp_key] override = @overrides[exp_key] - experiment = experiment(experiment_name.to_s, state) - if @switchbacks_active + # The index is keyed as experiment() keys it; exp_key is that key already. + experiment = state.index[exp_key] + if @switchbacks if !experiment.nil? && experiment.switchback - return NEEDS_CLOCK if now.nil? + return nil if now.nil? return switchback_assignment(experiment_name.to_s, experiment, custom, override, now) end @@ -1451,23 +1456,16 @@ def cached_or_new_assignment(experiment_name, state, now = nil) def resolve_variable_value(key, default_value, expose) key = key.to_s.to_sym winner = nil - now = nil attempts = 0 while true # rubocop:disable Style/InfiniteLoop -- no block allocation on the read path return default_value if attempts >= VARIABLE_WALK_ATTEMPTS attempts += 1 state = @state - # Read once per walk, so every switchback it resolves shares a reading. - now = @switchbacks_active ? now_millis : nil if now.nil? + # Read once per walk, so every switchback it resolves shares a reading + # (a refresh that installs the first switchback restarts the walk). + now = @switchbacks ? now_millis : nil winner = variable_assignment(key, expose, state, now) - if winner.equal?(NEEDS_CLOCK) - # A refresh installed the first switchback during the walk: it - # starts again at the reading taken now. - attempts -= 1 - now = now_millis - next - end visited = nil winner, visited = winner if winner.is_a?(Array) # A refresh, even one from a holdout's logger, restarts the walk. @@ -1505,8 +1503,7 @@ def variable_assignment(key, expose, state = @state, now = nil) while i < candidates.length # Resolved from the state current under the assignment lock, so a read # that a refresh overtook can't reinstall an old assignment. - assignment = assignment(candidates[i].data.name, now, true) - return NEEDS_CLOCK if assignment.equal?(NEEDS_CLOCK) + assignment = assignment(candidates[i].data.name, now) # As in java-sdk, visited candidates' holdouts precede the winner's exposure. if expose && !assignment.holdout_assignments.nil? && (!assignment.exposed || assignment.overridden) && holdouts_pending?(assignment) @@ -1616,7 +1613,9 @@ def variant_assigner(unit_type, unit_hash) # building?), and the next build or wait drops one left behind. def build_state(data) thread = Thread.current - nested = build_state_on_stack?(1) + # Only this thread adds or removes its own entry, so without one now + # there is none under the lock either, and the stack walk is skipped. + nested = @building_threads.key?(thread) && build_state_on_stack?(1) registered = false begin Thread.handle_interrupt(Object => :never) do @@ -1720,17 +1719,7 @@ def build_state_maps(data) end experiment_variables.unconditional = experiment_variables.rule_key.equal?(NO_RULES) && (experiment.audience.nil? || experiment.audience.empty?) - # Holdouts never apply to a switchback. - if experiment.respond_to?(:randomization_type) && experiment.randomization_type == SWITCHBACK - clusters = experiment.switchback_clusters - experiment_variables.switchback = true - experiment_variables.switchback_grid = switchback_grid(experiment) - experiment_variables.switchback_source_types = Absmartly::Switchback::Serving.source_types(clusters) - experiment_variables.switchback_source_paths = Absmartly::Switchback::Serving.source_paths(clusters) - experiment_variables.switchback_source_roots = experiment_variables.switchback_source_paths&.to_set(&:root_key)&.freeze - end - holdout_ids = experiment.holdout_ids unless holdouts_by_id.empty? || experiment_variables.switchback || - !experiment.respond_to?(:holdout_ids) + holdout_ids = experiment.holdout_ids unless holdouts_by_id.empty? || !experiment.respond_to?(:holdout_ids) if holdout_ids.is_a?(Array) && !holdout_ids.empty? holdouts = holdout_ids.filter_map { |id| holdouts_by_id[holdout_id(id)] }.uniq.sort_by { |h| holdout_id(h.id) } experiment_variables.holdouts = holdouts unless holdouts.empty? @@ -1785,17 +1774,42 @@ def build_state_maps(data) end end - State.new(data, index, index_variables, custom_fields) + state = State.new(data, index, index_variables, custom_fields) + mark_switchbacks(state) + end + + # Marks each switchback experiment of a built snapshot; a snapshot with + # one becomes a SwitchbackSnapshot. Holdouts never apply to a switchback. + # A custom deserializer's data may predate switchbacks, so the field is + # optional. + def mark_switchbacks(state) + experiments = state.data&.experiments + return state if experiments.nil? + + switchback_state = nil + experiments.each do |experiment| + next unless experiment.respond_to?(:randomization_type) && experiment.randomization_type == SWITCHBACK + + entry = state.index[experiment.name.to_sym] + next if entry.nil? || !entry.data.equal?(experiment) + + entry.switchback = switchback_entry(experiment) + entry.holdouts = nil + switchback_state ||= SwitchbackSnapshot.new(state.data, state.index, state.index_variables, state.custom_fields) + end + switchback_state || state end # Called right before state is installed, under the readiness lock (or # from the constructor): a switchback keeps its generation while it is # unchanged (see assign_switchback_generations). def prepare_switchbacks(state) - assign_switchback_generations(state.index, @state.index) + return if @switchbacks.nil? && !state.instance_of?(SwitchbackSnapshot) + # Set before the state, and kept once a switchback was installed: its # epochs must still be dropped. - @switchbacks_active ||= state.index.each_value.any?(&:switchback) + @switchbacks ||= SwitchbackState.new({}, 0, nil) + assign_switchback_generations(state.index, @state.index) end # A switchback keeps its generation while its previous definition was a @@ -1806,10 +1820,10 @@ def assign_switchback_generations(index, previous_index) next unless installed.switchback previous = previous_index[name] - installed.switchback_generation = if same_switchback_identity?(previous, installed) - previous.switchback_generation + installed.switchback.generation = if same_switchback_identity?(previous, installed) + previous.switchback.generation else - @switchback_generation += 1 + @switchbacks.generation += 1 end end end @@ -1822,11 +1836,18 @@ def same_switchback_identity?(previous, installed) a = previous.data b = installed.data - a.id == b.id && a.iteration == b.iteration && previous.switchback_grid == installed.switchback_grid && - ((!previous.switchback_source_paths.nil? && !installed.switchback_source_paths.nil?) || + a.id == b.id && a.iteration == b.iteration && previous.switchback.grid == installed.switchback.grid && + ((!previous.switchback.source_paths.nil? && !installed.switchback.source_paths.nil?) || a.unit_type == b.unit_type) end + def switchback_entry(experiment) + clusters = experiment.switchback_clusters + paths = Absmartly::Switchback::Serving.source_paths(clusters) + SwitchbackEntry.new(Absmartly::Switchback::Serving.source_types(clusters), paths, + paths&.to_set(&:root_key)&.freeze, nil, switchback_grid(experiment)) + end + def switchback_grid(experiment) [Experiment.ordered_clusters(experiment.switchback_clusters), experiment.switchback_cluster_values, experiment.switchback_start_at, experiment.switchback_period_ms, experiment.switchback_design_type] @@ -1846,7 +1867,7 @@ def switchback_schedule_servable?(experiment) # floor((now - startAt) / periodMs), or nil before the start, for an # unservable schedule and on the legacy path. def switchback_period(entry, now) - return nil if entry.switchback_source_paths.nil? || !switchback_schedule_servable?(entry.data) + return nil if entry.switchback.source_paths.nil? || !switchback_schedule_servable?(entry.data) start_at = entry.data.switchback_start_at now < start_at ? nil : (now - start_at).div(entry.data.switchback_period_ms) @@ -1861,11 +1882,11 @@ def switchback_seed(experiment) # units maps unit type names to uids and attributes is the attribute list # read, so a publish can resolve the cluster again from its own payload. def resolve_switchback_serving(entry, now, units = @units.transform_keys(&:to_s), attributes = @attributes) - if entry.switchback_source_paths.nil? + if entry.switchback.source_paths.nil? return Absmartly::Switchback::Serving.legacy(entry.data.unit_type, units) end - Absmartly::Switchback::Serving.resolve(entry.switchback_source_types, entry.switchback_source_paths, + Absmartly::Switchback::Serving.resolve(entry.switchback.source_types, entry.switchback.source_paths, entry.data.switchback_cluster_values, units) do |path| attribute = latest_attribute(path.root_key, now, attributes) attribute.nil? ? nil : path.resolve_attribute(attribute.value) @@ -1876,7 +1897,7 @@ def resolve_switchback_serving(entry, now, units = @units.transform_keys(&:to_s) # so a caller that later changes the object it set can't change the # cluster the slot served or the body its exposure is published with. def serving_snapshot(entry) - roots = entry.switchback_source_roots + roots = entry.switchback.source_roots return @attributes.dup if roots.nil? @attributes.map do |attribute| @@ -1927,8 +1948,8 @@ def latest_attribute(name, now, attributes) # its own slot; the bare-name slot serves before the anchor and for an # unservable schedule. Caller holds @assignment_mutex. def switchback_assignment(name, entry, custom, override, now) - epoch = @switchback_epochs[name] - drop_switchback_epoch(name) if !epoch.nil? && epoch.generation != entry.switchback_generation + epoch = @switchbacks.epochs[name] + drop_switchback_epoch(name) if !epoch.nil? && epoch.generation != entry.switchback.generation period = switchback_period(entry, now) cache_key = period.nil? ? name : "#{name}#{SWITCHBACK_KEY_SEPARATOR}#{period}" @@ -2072,14 +2093,14 @@ def switchback_assignment_current?(assignment, entry, custom, override) # The unit a switchback with no serving unit is recorded under: the first # linked type of a readable map, otherwise the declared unitType. def switchback_fallback_unit_type(entry) - entry.switchback_source_paths.nil? ? entry.data.unit_type : entry.switchback_source_types[0] + entry.switchback.source_paths.nil? ? entry.data.unit_type : entry.switchback.source_types[0] end # Drops every slot of an experiment's epoch once its definition is gone, # no longer a switchback, or of another generation. Caller holds # @assignment_mutex. def drop_switchback_epoch(name) - epoch = @switchback_epochs.delete(name) + epoch = @switchbacks.epochs.delete(name) return if epoch.nil? epoch.periods.each { |period| @assignment_cache.delete("#{name}#{SWITCHBACK_KEY_SEPARATOR}#{period}") } @@ -2089,7 +2110,7 @@ def drop_switchback_epoch(name) # At most SWITCHBACK_RETAINED_PERIODS period indices per experiment; the # lowest one other than the period just installed is evicted. def retain_switchback_period(name, entry, period) - epoch = (@switchback_epochs[name] ||= SwitchbackEpoch.new(entry.switchback_generation, [])) + epoch = (@switchbacks.epochs[name] ||= SwitchbackEpoch.new(entry.switchback.generation, [])) return if period.nil? || epoch.periods.include?(period) epoch.periods.push(period).sort! @@ -2152,10 +2173,7 @@ def init_common(clock, config, data_provider, event_handler, event_logger, @failed_marked = false @exposing = {}.compare_by_identity @exposure_condvar = ConditionVariable.new - @switchback_epochs = {} - @switchbacks_active = false - @switchback_generation = 0 - @switchback_exposures = nil + @switchbacks = nil @assignments = {} @clock = clock.is_a?(String) ? Time.iso8601(clock) : clock @fixed_millis = nil @@ -2275,9 +2293,8 @@ def initialize end class ExperimentVariables - attr_accessor :data, :variables, :rules, :rule_key, :unconditional, :holdouts, - :switchback, :switchback_source_types, :switchback_source_paths, :switchback_source_roots, - :switchback_generation, :switchback_grid + # switchback is nil, or the SwitchbackEntry of a switchback experiment. + attr_accessor :data, :variables, :rules, :rule_key, :unconditional, :holdouts, :switchback # Every field is set up front so all instances share one object shape and # the cached read path's attribute reads stay monomorphic. @@ -2288,12 +2305,7 @@ def initialize @rule_key = nil @unconditional = nil @holdouts = nil - @switchback = false - @switchback_source_types = nil - @switchback_source_paths = nil - @switchback_source_roots = nil - @switchback_generation = nil - @switchback_grid = nil + @switchback = nil end end diff --git a/lib/hashing.rb b/lib/hashing.rb index 0e1352fd..ea03be58 100644 --- a/lib/hashing.rb +++ b/lib/hashing.rb @@ -16,8 +16,11 @@ class Hashing # numbers (BigDecimal, Rational) hash from to_s, as in v1.3.0. Text is # hashed as UTF-8, whatever its encoding (see to_utf8). def self.hash_unit(value) - unit = value.is_a?(Float) ? number_to_fixed0(value) : value - base64_url_no_padding(Digest::MD5.digest(to_utf8(unit).b)) + unit = value.is_a?(Float) ? number_to_fixed0(value) : value.to_s + # ASCII text has the same bytes in UTF-8 and every ASCII-compatible + # encoding, so only other text is transcoded. + unit = to_utf8(unit) unless unit.ascii_only? + base64_url_no_padding(Digest::MD5.digest(unit.b)) end # The text JavaScript's Number#toFixed(0) produces, which the JS SDK hashes diff --git a/spec/context_switchback_cluster_spec.rb b/spec/context_switchback_cluster_spec.rb index fe794a37..d6614b76 100644 --- a/spec/context_switchback_cluster_spec.rb +++ b/spec/context_switchback_cluster_spec.rb @@ -974,7 +974,7 @@ def transform_values! expect(logged.map(&:first)).to eq([ContextEventLogger::EVENT_TYPE::PUBLISH] * 2) expect(logged[0][1].goals.map(&:name)).to eq(["goal"]) expect(logged[1][1].exposures.map(&:name)).to eq(["exp_sb"]) - expect(context.instance_variable_get(:@switchback_exposures)).to be_nil + expect(context.instance_variable_get(:@switchbacks).exposures).to be_nil allow(context).to receive(:served_at?).and_call_original context.track("next") context.publish diff --git a/spec/context_switchback_spec.rb b/spec/context_switchback_spec.rb index 7f17a1f1..aa396ad8 100644 --- a/spec/context_switchback_spec.rb +++ b/spec/context_switchback_spec.rb @@ -440,9 +440,12 @@ def serialized_publish(context) clock.now = ANCHOR + HOUR clock.next_read = ANCHOR + HOUR - 1 end - expect(worker.value).to eq([EXPECTED_2_ARMS[0], []]) + # A variable read's walk starts again on the refreshed data, at a reading of its own; the + # value and the exposure still come from that one reading. + arm, at = api == :variable_value ? [EXPECTED_2_ARMS[1], ANCHOR + HOUR] : [EXPECTED_2_ARMS[0], ANCHOR + HOUR - 1] + expect(worker.value).to eq([arm, []]) expect(EXPECTED_2_ARMS[0]).not_to eq(EXPECTED_2_ARMS[1]) - expected = api == :peek_treatment ? [] : [sb_exposure(1, "exp_sb", EXPECTED_2_ARMS[0], ANCHOR + HOUR - 1, true, true)] + expected = api == :peek_treatment ? [] : [sb_exposure(1, "exp_sb", arm, at, true, true)] expect(published_exposures(context)).to eq(expected) end end @@ -514,7 +517,7 @@ def evaluate(*) refresh_to(context, [unit_twin(switchback(fullOnVariant: 1))]) expect(context.treatment("exp_sb")).to eq(1) expect(context.pending_count).to eq(2) - expect(context.instance_variable_get(:@switchback_epochs)).to be_empty + expect(context.instance_variable_get(:@switchbacks).epochs).to be_empty end it "starts the grid when a refresh sets the start" do @@ -1421,16 +1424,18 @@ def queue_exposure(assignment) context.peek_variable_value("banner.border", 0) # Only the exposure itself reads the clock, once. expect(clock).to have_received(:call).once - %i[expose_assignment separate_switchback_exposures].each do |helper| + %i[publish_with_switchbacks separate_switchback_exposures switchback_assignment].each do |helper| allow(context).to receive(helper).and_call_original end context.treatment("exp_test_ab") context.peek_treatment("exp_test_ab") context.variable_value("banner.border", 0) context.publish - expect(context).not_to have_received(:expose_assignment) + expect(context).not_to have_received(:publish_with_switchbacks) expect(context).not_to have_received(:separate_switchback_exposures) - expect(context.instance_variable_get(:@switchback_epochs)).to be_empty + expect(context).not_to have_received(:switchback_assignment) + # No switchback state is allocated for a payload without one. + expect(context.instance_variable_get(:@switchbacks)).to be_nil end end end From aa972e7cb54c01129c140cb847311aeee6d9e4d2 Mon Sep 17 00:00:00 2001 From: lux worker Date: Mon, 30 Nov 2026 23:34:40 +0000 Subject: [PATCH 05/15] test: kill the surviving switchback mutants; identity sets for delivered events Mutation run over the switchback paths (lib/absmartly/switchback.rb, the switchback methods of lib/context.rb, lib/hashing.rb): 419 mutants, 79 survived the switchback specs, 45 the full suite. Each non-equivalent survivor now has a killing test (arm-count bound and message, index and map steps, scalar roots, sibling-visited values, value-less later units, false in an allow-list, override equal to the schedule, cleared override, out-of-range override variables, empty audience, a later same-name unit experiment, copy depth, partial rejection of a multi-request publish, legacy to cluster-map epoch change, absent serving, reads after close, US-ASCII/binary unit bytes). remove_delivered and forget_switchback_exposures use identity Sets. Co-Authored-By: Claude Opus 5.5 --- lib/context.rb | 16 ++-- spec/context_switchback_cluster_spec.rb | 22 +++++ spec/context_switchback_spec.rb | 110 ++++++++++++++++++++++++ spec/parity_spec.rb | 7 ++ spec/switchback_internals_spec.rb | 31 ++++++- 5 files changed, 177 insertions(+), 9 deletions(-) diff --git a/lib/context.rb b/lib/context.rb index 44218a33..2f5e4f2f 100644 --- a/lib/context.rb +++ b/lib/context.rb @@ -776,14 +776,14 @@ def remove_published((exposures, exposure_count, achievements, achievement_count # Removes the events of the delivered requests of a partly delivered # switchback publish; the rest stay queued for the next attempt. def remove_delivered((exposures, _, achievements, _), events) - sent = {}.compare_by_identity + sent = Set.new.compare_by_identity events.each do |event| - event.exposures&.each { |e| sent[e] = true } - event.goals&.each { |g| sent[g] = true } + event.exposures&.each { |e| sent << e } + event.goals&.each { |g| sent << g } end @queue_mutex.synchronize do - @exposures.reject! { |e| sent.key?(e) } if @exposures.equal?(exposures) - @achievements.reject! { |g| sent.key?(g) } if @achievements.equal?(achievements) + @exposures.reject! { |e| sent.include?(e) } if @exposures.equal?(exposures) + @achievements.reject! { |g| sent.include?(g) } if @achievements.equal?(achievements) @pending_count = @exposures.size + @achievements.size forget_switchback_exposures end @@ -796,9 +796,9 @@ def forget_switchback_exposures switchback_exposures = @switchbacks&.exposures return if switchback_exposures.nil? - queued = {}.compare_by_identity - @exposures.each { |e| queued[e] = true } - switchback_exposures.delete_if { |e, _| !queued.key?(e) } + # compare_by_identity before adding: it would drop members added first. + queued = Set.new.compare_by_identity.merge(@exposures) + switchback_exposures.delete_if { |e, _| !queued.include?(e) } @switchbacks.exposures = nil if switchback_exposures.empty? end diff --git a/spec/context_switchback_cluster_spec.rb b/spec/context_switchback_cluster_spec.rb index d6614b76..22e35583 100644 --- a/spec/context_switchback_cluster_spec.rb +++ b/spec/context_switchback_cluster_spec.rb @@ -662,6 +662,28 @@ def multi_request_context expect(context.pending_count).to eq(0) end + # A later request the collector rejects keeps only that request's events queued. + it "keeps only the rejected request's events after a later request fails" do + context = multi_request_context + publisher = context.send(:event_handler) + delivered = [] + attempts = 0 + allow(publisher).to receive(:publish) do |_ctx, event| + attempts += 1 + next OpenStruct.new(success?: false, status: 503) if attempts == 2 + + delivered << event + OpenStruct.new(success?: true) + end + result = context.publish + expect(result.success?).to be(false) + expect(delivered.map { |e| e.goals&.map(&:name) }).to eq([["goal"]]) + expect(context.pending_count).to eq(1) + context.publish + expect(delivered.last.exposures.map(&:name)).to eq(["exp_sb"]) + expect(context.pending_count).to eq(0) + end + it "logs the error a raising publisher raises before it propagates, on both paths" do [false, true].each do |multi| context = multi ? multi_request_context : create_context(attribute_switchback("city")) diff --git a/spec/context_switchback_spec.rb b/spec/context_switchback_spec.rb index aa396ad8..824a5a81 100644 --- a/spec/context_switchback_spec.rb +++ b/spec/context_switchback_spec.rb @@ -1176,6 +1176,19 @@ def evaluate_parsed_rules(*args) expect(published_exposures(context)).to eq([sb_exposure(1, "exp_sb", 0, ANCHOR, true, false)]) end + # Moving between the legacy path and a cluster map is an epoch change, even with the same + # unitType: the legacy slot (a silent ineligible control) is not kept for the cluster schedule. + it "starts a new epoch when a legacy switchback gains a cluster map" do + context = create_context([switchback(switchbackClusters: nil)]) + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(0) + expect(context.pending_count).to eq(0) + + refresh_to(context, [switchback]) + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(published_exposures(context)).to eq([sb_exposure(1, "exp_sb", EXPECTED_2_ARMS[0], ANCHOR + 10, true, true)]) + end + # An override with no serving unit is exposed under the declared unitType on the legacy path. it "exposes an override on a legacy switchback under the declared unitType" do context = create_context([switchback(1, "exp_missing_map", 2, HOUR, unitType: "user_id", switchbackClusters: nil), @@ -1280,6 +1293,16 @@ def evaluate(_audience, _attributes) # An exposed override of a switchback without a linked unit is kept when a unit is set: it # published, so replacing it would publish the override again. + # Without a linked unit the slot is a silent ineligible control under the first linked type. + it "resolves a switchback without a linked unit to a silent ineligible control" do + context = create_context([switchback], units: { "user_id" => "u1" }) + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(0) + slot = context.send(:switchback_resolution_for_test, "exp_sb") + expect([slot.unit_type, slot.eligible, slot.switchback_silent, slot.assigned]).to eq([UNIT_TYPE, false, true, false]) + expect(context.pending_count).to eq(0) + end + it "keeps an exposed override when a linked unit is set later" do context = create_context([switchback], units: { "user_id" => "u1" }, overrides: { "exp_sb" => 1 }) clock.now = ANCHOR + 10 @@ -1290,6 +1313,93 @@ def evaluate(_audience, _attributes) expect(published_exposures(context).map(&:unit)).to eq([UNIT_TYPE]) end + # An override equal to the variant a slot already serves still rebuilds it as an override, so + # its exposure is flagged overridden. + it "flags an override equal to the scheduled variant as overridden" do + context = create_context([switchback]) + clock.now = ANCHOR + 10 + scheduled = context.peek_treatment("exp_sb") + context.set_override("exp_sb", scheduled) + expect(context.treatment("exp_sb")).to eq(scheduled) + expect(published_exposures(context).map { |e| [e.variant, e.overridden] }).to eq([[scheduled, true]]) + end + + # Clearing an override serves the schedule again, within the same period. + it "serves the schedule again once an override is cleared" do + context = create_context([switchback]) + clock.now = ANCHOR + 10 + scheduled = context.peek_treatment("exp_sb") + context.set_override("exp_sb", 1 - scheduled) + expect(context.treatment("exp_sb")).to eq(1 - scheduled) + context.set_override("exp_sb", nil) + expect(context.treatment("exp_sb")).to eq(scheduled) + end + + # An override outside the variants reads no variant's variables (Ruby's negative index would + # read the last one). + it "reads no variables for an override outside the variants" do + context = create_context([switchback], overrides: { "exp_sb" => -1 }) + clock.now = ANCHOR + 10 + expect(context.variable_value("sb.arm", "default")).to eq("default") + context = create_context([switchback], overrides: { "exp_sb" => 2 }) + expect(context.variable_value("sb.arm", "default")).to eq("default") + end + + # An empty audience is not evaluated, so a custom matcher never sees it. + it "does not evaluate an empty audience" do + matcher = Class.new(AudienceMatcher) do + def evaluate(audience, _attributes) + raise "evaluated #{audience.inspect}" + end + end.new(DefaultAudienceDeserializer.new) + context = create_context([switchback(audience: ""), unit_twin(switchback(2, "exp_unit", audience: ""))], + audience_matcher: matcher) + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect { context.treatment("exp_unit") }.not_to raise_error + end + + # With two experiments of one name the payload's last one is indexed; an earlier switchback of + # that name does not make it a switchback. + it "serves a later unit experiment that shares an earlier switchback's name as a unit experiment" do + context = create_context([switchback, unit_twin(switchback(fullOnVariant: 1))]) + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(1) + expect(context.instance_variable_get(:@switchbacks)).to be_nil + end + + # A period copies a cluster source only to the depth a path can read; deeper parts are kept. + it "copies cluster source values only to the depth a path reads" do + max = Absmartly::Switchback::AttributePath::MAX_DEPTH + leaf = { "leaf" => "x" } + root = leaf + (max + 1).times { root = { "n" => root } } + originals = [root] + originals << originals.last["n"] while originals.last.key?("n") + context = create_context([switchback]) + copy = context.send(:copy_attribute_value, root) + copies = [copy] + copies << copies.last["n"] while copies.last.key?("n") + expect(copies.length).to eq(originals.length) + # Depths 0..MAX_DEPTH are copies; the value at MAX_DEPTH + 1 is the caller's own. + (0..max).each { |depth| expect(copies[depth]).not_to equal(originals[depth]), depth.to_s } + expect(copies[max + 1]).to equal(originals[max + 1]) + list = [[["x"]]] + expect(context.send(:copy_attribute_value, list)[0][0]).not_to equal(list[0][0]) + end + + # As in 1.4.0, reads raise once the context is closed, an exposed experiment included. + it "raises on treatment after close, for an exposed switchback and unit experiment too" do + context = create_context([switchback, unit_twin(switchback(2, "exp_unit"))]) + clock.now = ANCHOR + 10 + context.treatment("exp_sb") + context.treatment("exp_unit") + context.close + %w[exp_sb exp_unit].each do |name| + expect { context.treatment(name) }.to raise_error(IllegalStateException, "ABSmartly Context is closed") + end + end + # A peeked (unexposed) override of a switchback without a linked unit is resolved again once a # linked unit is set, so its exposure goes under that unit, not the first linked type. it "publishes a peeked override under the linked unit set later" do diff --git a/spec/parity_spec.rb b/spec/parity_spec.rb index 6b61bc8d..607f9c56 100644 --- a/spec/parity_spec.rb +++ b/spec/parity_spec.rb @@ -64,6 +64,13 @@ expect(Hashing.hash_unit(wtf8)).to eq(lone_surrogate_hash) end + # Text tagged US-ASCII or binary is read as its UTF-8 bytes, CESU-8 pairs included. + it "hashes US-ASCII- and binary-tagged bytes as the UTF-8 text they hold" do + expect(Hashing.hash_unit("\xC3\xA9".dup.force_encoding("US-ASCII"))).to eq(Hashing.hash_unit("\u00E9")) + cesu = "\u{1F600}".encode("UTF-16BE").unpack("n*").map { |u| [u].pack("U") }.join.b + expect(Hashing.hash_unit(cesu)).to eq(Hashing.hash_unit("\u{1F600}")) + end + it "replaces other invalid bytes with U+FFFD" do invalid = "a\xFFb".dup.force_encoding("UTF-8") expect(Hashing.to_utf8(invalid).bytes).to eq([97, 239, 191, 189, 98]) diff --git a/spec/switchback_internals_spec.rb b/spec/switchback_internals_spec.rb index 44f2744a..ebed88f3 100644 --- a/spec/switchback_internals_spec.rb +++ b/spec/switchback_internals_spec.rb @@ -78,7 +78,9 @@ def exact_long(value) it "rejects fewer than two arms" do expect { Assigner.assign("u", 0, 0, 1) }.to raise_error(ArgumentError) - expect { Assigner.fisher_yates_permutation(0, 0) }.to raise_error(ArgumentError) + expect { Assigner.fisher_yates_permutation(0, 0) }.to raise_error(ArgumentError, "arm_count must be >= 2, got 0") + expect { Assigner.assign("u", 0, 0, 2.0) }.to raise_error(ArgumentError) + expect(Assigner.fisher_yates_permutation(2, 0).sort).to eq([0, 1]) end # The cycle is Java's floorDiv(period, arms) and the slot its floorMod, including negative @@ -155,6 +157,11 @@ def parse(path) "name" => "scalar" } expect(parse("geo/0/city").resolve(attributes)).to be_nil expect(parse("items/1/city").resolve(attributes)).to be_nil + # One past the end is out of range; an index into a map or a scalar reads nothing. + expect(parse("items/1/city").resolve({ "items" => [{ "city" => "a" }] })).to be_nil + expect(parse("items/0/city").resolve({ "items" => [{ "city" => "a" }] })).to eq("a") + expect(parse("items/0/x").resolve({ "items" => { 0 => { "x" => "map" } } })).to be_nil + expect(parse("items/0/x").resolve({ "items" => "abc" })).to be_nil expect(parse("name/x").resolve(attributes)).to be_nil expect(parse("missing/x").resolve(attributes)).to be_nil expect(parse("items/-0/city").resolve(attributes)).to eq("Lisbon") @@ -180,11 +187,20 @@ def parse(path) # A value reached twice through siblings is not a cycle. shared = { "a" => "b" } expect(path.resolve_attribute({ "city" => "Porto", "x" => shared, "y" => shared })).to eq("Porto") + # Nor is one nested under itself without a back reference: a container is on the path only + # while it is being visited. + inner = { "z" => 1 } + expect(path.resolve_attribute({ "city" => "Porto", "x" => { "y" => inner }, "w" => [inner] })).to eq("Porto") end # Values are read through their JSON encoding, as the Collector reads the published # attribute: Symbol keys and values become strings, a Float stays a Float. it "reads values through their JSON encoding" do + # A scalar root is its own JSON value; a path below it reads nothing. + expect(parse("geo").resolve_attribute(17)).to eq(17) + expect(parse("geo").resolve_attribute(true)).to be(true) + expect(parse("geo").resolve_attribute(false)).to be(false) + expect(parse("geo/city").resolve_attribute(false)).to be_nil path = parse("geo/city") expect(path.resolve_attribute({ geo: :x, city: :Porto })).to eq("Porto") expect(path.resolve_attribute({ "city" => 3.0 })).to eq(3.0) @@ -234,6 +250,17 @@ def resolve(types, paths, allowed, units, attributes) expect([serving.status, serving.unit_type, serving.cluster_key]).to eq([Serving::ELIGIBLE, "session_id", "s-1"]) end + # A linked unit whose path gives no value is skipped, not taken as the key. + it "serves the next unit's value when an earlier linked unit has none" do + serving = resolve(%w[session_id user_id], %w[session_store user_store], nil, + { "session_id" => "x1", "user_id" => "u1" }, { "session_store" => true, "user_store" => "s-2" }) + expect([serving.status, serving.unit_type, serving.cluster_key]).to eq([Serving::ELIGIBLE, "user_id", "s-2"]) + # A later linked unit without a value does not disagree with the one that serves. + later = resolve(%w[session_id user_id], %w[session_store user_store], nil, + { "session_id" => "x1", "user_id" => "u1" }, { "session_store" => "s-1" }) + expect([later.status, later.unit_type, later.cluster_key]).to eq([Serving::ELIGIBLE, "session_id", "s-1"]) + end + it "skips a unit without a value, and a disagreement is ineligible under the first unit" do skipped = resolve(%w[session_id user_id], %w[session_store user_store], nil, { "session_id" => "x1", "user_id" => "u1" }, { "user_store" => "s-2" }) @@ -258,6 +285,8 @@ def resolve(types, paths, allowed, units, attributes) expect(Serving.allowed?("a", "a")).to be(false) # Scalars match their JSON text, as Jackson coerces them into java-sdk's String[]. expect(Serving.allowed?([true], "true")).to be(true) + expect(Serving.allowed?([false], "false")).to be(true) + expect(Serving.allowed?([false], "true")).to be(false) expect(Serving.allowed?([1.5], "1.5")).to be(true) expect(Serving.allowed?([nil, { "a" => "a" }, ["a"], Float::NAN], "a")).to be(false) expect(Serving.allowed?([{ "a" => "a" }], '{"a"=>"a"}')).to be(false) From 771a4dae4305847518d3483f42c120aa4a9c0eed Mon Sep 17 00:00:00 2001 From: lux worker Date: Mon, 30 Nov 2026 23:36:14 +0000 Subject: [PATCH 06/15] test: pin the epoch change when a switchback loses its cluster map Co-Authored-By: Claude Opus 5.5 --- spec/context_switchback_spec.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/spec/context_switchback_spec.rb b/spec/context_switchback_spec.rb index 824a5a81..d0bd5f79 100644 --- a/spec/context_switchback_spec.rb +++ b/spec/context_switchback_spec.rb @@ -1189,6 +1189,18 @@ def evaluate_parsed_rules(*args) expect(published_exposures(context)).to eq([sb_exposure(1, "exp_sb", EXPECTED_2_ARMS[0], ANCHOR + 10, true, true)]) end + # And back: losing the cluster map drops the served slot for a silent legacy control. + it "starts a new epoch when a switchback loses its cluster map" do + context = create_context([switchback]) + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(EXPECTED_2_ARMS[0]) + expect(context.variable_value("sb.arm", -1)).to eq(EXPECTED_2_ARMS[0]) + + refresh_to(context, [switchback(switchbackClusters: nil)]) + expect(context.treatment("exp_sb")).to eq(0) + expect(context.send(:switchback_resolution_for_test, "exp_sb").switchback_silent).to be(true) + end + # An override with no serving unit is exposed under the declared unitType on the legacy path. it "exposes an override on a legacy switchback under the declared unitType" do context = create_context([switchback(1, "exp_missing_map", 2, HOUR, unitType: "user_id", switchbackClusters: nil), From b88402c914b0865215ae18ef98306871919b8123 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 1 Dec 2026 09:50:27 +0000 Subject: [PATCH 07/15] fix: a Float switchbackClusterValues entry never matches a cluster key Owner rule (2026-12-01): switchbacks do not support floats. An allow-list entry that is a JSON float (2.5, 3.0) admits no cluster; String entries match as is and Integer entries by their decimal text (17 admits "17"); booleans are unchanged. The attribute side already gives no key for a Float. Regressions: [2.5] vs "2.5", [3.0] vs "3" and "3.0" never match, [17] vs "17" does, end to end through a decoded payload too. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 2 +- lib/absmartly/switchback.rb | 8 ++++---- spec/context_switchback_cluster_spec.rb | 27 +++++++++++++++++++++++++ spec/switchback_internals_spec.rb | 7 ++++++- 5 files changed, 39 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 739afefd..a7411064 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ Adds switchback experiments on top of 1.4.0, without breaking it: every 1.4.0 class, method signature, return value, error and behaviour is kept, and experiments that are not switchbacks are assigned, exposed and published as in 1.4.0. Only the timestamps and two unit-hashing cases change, as each Fixed entry says. ### Added -- Switchback experiments, served as the Collector and the Java SDK serve them (the R33 cluster-defined contract). An experiment with `randomizationType: "switchback"` lists in `switchbackClusters`, in order, the unit types it is linked to and the attribute path holding each one's cluster value (`/` nests, a quoted segment is a literal key, an integer segment indexes an array). The first linked unit, in declared order, whose attribute gives a value serves the experiment and its exposure; the value is the cluster key, used raw (never hashed): a non-empty String as is, an Integer as its decimal text, while a Float (`3.0` included), boolean, Hash, Array, `""` or `nil` gives none. The variant is the platform's balanced-block draw for the period `floor((now - switchbackStartAt) / switchbackPeriodMs)` and the experiment's 64-bit seed. No value, disagreeing units or a value outside `switchbackClusterValues` give control and no exposure; so do the time before `switchbackStartAt` and an unservable schedule (a start that is not hour aligned, a period of 0 or less, fewer than two arms), where rules, a strict audience and full-on still apply. Overrides, assignment rules (a split rule over the serving unit), strict audiences, full-on, traffic (on the serving unit) and custom assignments apply in the Collector's order; holdouts never apply to a switchback. One exposure is sent per experiment and period while its assignment is unchanged (a custom assignment, override or refresh that rebuilds it within the period, or a clock that returns to a period no longer among the two most recent, sends one more), stamped with the time that chose the period, and the cluster value is read once per period. Changing a unit's cluster attribute mid-period, before its exposure, is not supported: callers set it before the first read, and a change takes effect in the next period. A period keeps a copy of the cluster-source attribute values it read (a String, Array or Hash, to the depth a path reads), so changing a value passed to `set_attribute` in place does not change the cluster it served or the attributes its own exposure request carries; other attributes are not copied, and an in-place change to a key of an identity-compared Hash is not supported. The Collector resolves the serving unit and cluster again from the published units and attributes at `exposedAt`, so a switchback exposure that the batch would credit to another unit or cluster (an attribute changed within the period, a unit set afterwards, a write in the exposure's millisecond, a clock that stepped back) is published in a request of its own, with the units and attributes its period read and its own `exposedAt`; `publish` then sends more than one request. A string cluster value keys by its published UTF-8 text. The new experiment fields (`randomization_type`, `switchback_clusters`, `switchback_cluster_values`, `switchback_start_at`, `switchback_period_ms`, `switchback_carryover_duration_ms`, `switchback_burn_in_duration_ms`, `switchback_burn_out_duration_ms`, `switchback_design_type`, `switchback_estimand`) are optional; payloads without switchbacks assign, expose and publish as in 1.4.0 (one request per `publish`) and read no extra clock to do so. +- Switchback experiments, served as the Collector and the Java SDK serve them (the R33 cluster-defined contract). An experiment with `randomizationType: "switchback"` lists in `switchbackClusters`, in order, the unit types it is linked to and the attribute path holding each one's cluster value (`/` nests, a quoted segment is a literal key, an integer segment indexes an array). The first linked unit, in declared order, whose attribute gives a value serves the experiment and its exposure; the value is the cluster key, used raw (never hashed): a non-empty String as is, an Integer as its decimal text, while a Float (`3.0` included), boolean, Hash, Array, `""` or `nil` gives none. The variant is the platform's balanced-block draw for the period `floor((now - switchbackStartAt) / switchbackPeriodMs)` and the experiment's 64-bit seed. No value, disagreeing units or a value outside `switchbackClusterValues` give control and no exposure. That allow-list matches String entries as is and Integer (and boolean) entries by their decimal text (`17` admits `"17"`); switchbacks do not support floats, so a Float entry (`2.5`, `3.0`) never matches any cluster key; so do the time before `switchbackStartAt` and an unservable schedule (a start that is not hour aligned, a period of 0 or less, fewer than two arms), where rules, a strict audience and full-on still apply. Overrides, assignment rules (a split rule over the serving unit), strict audiences, full-on, traffic (on the serving unit) and custom assignments apply in the Collector's order; holdouts never apply to a switchback. One exposure is sent per experiment and period while its assignment is unchanged (a custom assignment, override or refresh that rebuilds it within the period, or a clock that returns to a period no longer among the two most recent, sends one more), stamped with the time that chose the period, and the cluster value is read once per period. Changing a unit's cluster attribute mid-period, before its exposure, is not supported: callers set it before the first read, and a change takes effect in the next period. A period keeps a copy of the cluster-source attribute values it read (a String, Array or Hash, to the depth a path reads), so changing a value passed to `set_attribute` in place does not change the cluster it served or the attributes its own exposure request carries; other attributes are not copied, and an in-place change to a key of an identity-compared Hash is not supported. The Collector resolves the serving unit and cluster again from the published units and attributes at `exposedAt`, so a switchback exposure that the batch would credit to another unit or cluster (an attribute changed within the period, a unit set afterwards, a write in the exposure's millisecond, a clock that stepped back) is published in a request of its own, with the units and attributes its period read and its own `exposedAt`; `publish` then sends more than one request. A string cluster value keys by its published UTF-8 text. The new experiment fields (`randomization_type`, `switchback_clusters`, `switchback_cluster_values`, `switchback_start_at`, `switchback_period_ms`, `switchback_carryover_duration_ms`, `switchback_burn_in_duration_ms`, `switchback_burn_out_duration_ms`, `switchback_design_type`, `switchback_estimand`) are optional; payloads without switchbacks assign, expose and publish as in 1.4.0 (one request per `publish`) and read no extra clock to do so. ### Changed - Experiments with `randomizationType: "switchback"` are served as switchbacks. 1.4.0 served a switchback that has a `unitType` as an ordinary experiment on that unit (a sticky variant that ignores clusters and periods). Who moves: units in running switchback experiments, which move to their cluster's schedule; their exposures move to the serving unit and to one per period while the assignment is unchanged. diff --git a/README.md b/README.md index 59336435..0dab14a8 100644 --- a/README.md +++ b/README.md @@ -346,7 +346,7 @@ context.treatment("delivery_fee_test") # the variant of cluster "lisbon" ``` - The experiment names, in order, the unit types it is linked to and the attribute path holding each one's cluster value. The first linked unit, in that order, whose attribute has a value serves the experiment; its exposure is sent under that unit. -- A cluster value is a non-empty string, used as is, or an Integer, keyed by its decimal text. A Float (even `3.0`), `true`/`false`, a Hash, an Array, `""` and `nil` give no value. +- A cluster value is a non-empty string, used as is, or an Integer, keyed by its decimal text. A Float (even `3.0`), `true`/`false`, a Hash, an Array, `""` and `nil` give no value. Switchbacks do not support floats on the experiment side either: a Float entry in the allowed cluster values (`2.5`, `3.0`) matches no cluster. - With no value, linked units that disagree, or a value the experiment does not allow, the unit gets control (variant 0) and no exposure is sent. Without a unit of a linked type, the experiment does not apply. - Before the experiment's start the unit gets control and no exposure is sent; an assignment rule, a strict audience mismatch and full-on still apply. - A period keeps a copy of the cluster attribute values it read, so changing a value you passed to `set_attribute` in place (a String's text, a Hash or Array entry) does not change the cluster served. Changing a key of an identity-compared Hash (`compare_by_identity`) in place is not supported. Set a new value with `set_attribute` instead. diff --git a/lib/absmartly/switchback.rb b/lib/absmartly/switchback.rb index 8e3e6549..4d746ec9 100644 --- a/lib/absmartly/switchback.rb +++ b/lib/absmartly/switchback.rb @@ -291,9 +291,10 @@ def self.legacy(unit_type, units) end # nil or [] admits every value, as in the Collector. Any other non-Array - # admits none. A scalar entry matches its JSON text, as Jackson coerces - # it into the Java SDK's String[] (17 as "17", true as "true", 1.5 as - # "1.5"); an object or array entry matches nothing. + # admits none. A String entry matches as is, an Integer or boolean entry + # its JSON text (17 as "17", true as "true"). Switchbacks do not support + # floats (owner rule), so a Float entry (2.5, 3.0) never matches; nor + # does an object or array entry. def self.allowed?(allowed_values, key) return true if allowed_values.nil? || (allowed_values.is_a?(Array) && allowed_values.empty?) return false unless allowed_values.is_a?(Array) @@ -305,7 +306,6 @@ def self.allowed_text(allowed) case allowed when String then allowed when Integer, true, false then allowed.to_s - when Float then allowed.finite? ? allowed.to_s : nil end end diff --git a/spec/context_switchback_cluster_spec.rb b/spec/context_switchback_cluster_spec.rb index 22e35583..dd0e63b9 100644 --- a/spec/context_switchback_cluster_spec.rb +++ b/spec/context_switchback_cluster_spec.rb @@ -206,6 +206,33 @@ def expose_and_publish(context) expect(missing.pending_count).to eq(0) end + # Switchbacks do not support floats (owner rule): a decoded Float allow-list entry admits no + # cluster, integral or not, while an Integer entry admits its decimal text. + it "admits no cluster through a Float allow-list entry" do + [[[2.5], "2.5"], [[3.0], "3"], [[3.0], "3.0"], [[3.0], 3]].each do |allowed, value| + clock.now = ANCHOR + context = create_context(attribute_switchback("city", switchbackClusterValues: allowed)) + context.set_attribute("city", value) + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(0), [allowed, value].inspect + # An ineligible cluster is control with no exposure. + expect(context.pending_count).to eq(0), [allowed, value].inspect + end + + [[[17], "17"], [[17], 17]].each do |allowed, value| + clock.now = ANCHOR + context = create_context(attribute_switchback("city", switchbackClusterValues: allowed)) + context.set_attribute("city", value) + clock.now = ANCHOR + 10 + expect(context.treatment("exp_sb")).to eq(expected("17", 0)), [allowed, value].inspect + expect(published_exposures(context).map(&:eligible)).to eq([true]), [allowed, value].inspect + # Period 1 draws a variant other than control for "17". + clock.now = ANCHOR + HOUR + expect(context.treatment("exp_sb")).to eq(expected("17", 1)), [allowed, value].inspect + expect(expected("17", 1)).not_to eq(0) + end + end + # The Collector reads the published JSON text, so a UTF-16 string keys like its UTF-8 twin, for # the draw and the allow-list. it "keys a string by its published UTF-8 text" do diff --git a/spec/switchback_internals_spec.rb b/spec/switchback_internals_spec.rb index ebed88f3..ae67e6a3 100644 --- a/spec/switchback_internals_spec.rb +++ b/spec/switchback_internals_spec.rb @@ -287,7 +287,12 @@ def resolve(types, paths, allowed, units, attributes) expect(Serving.allowed?([true], "true")).to be(true) expect(Serving.allowed?([false], "false")).to be(true) expect(Serving.allowed?([false], "true")).to be(false) - expect(Serving.allowed?([1.5], "1.5")).to be(true) + # Switchbacks do not support floats: a Float entry never matches, integral or not. + expect(Serving.allowed?([1.5], "1.5")).to be(false) + expect(Serving.allowed?([2.5], "2.5")).to be(false) + expect(Serving.allowed?([3.0], "3")).to be(false) + expect(Serving.allowed?([3.0], "3.0")).to be(false) + expect(Serving.allowed?([17], "17")).to be(true) expect(Serving.allowed?([nil, { "a" => "a" }, ["a"], Float::NAN], "a")).to be(false) expect(Serving.allowed?([{ "a" => "a" }], '{"a"=>"a"}')).to be(false) expect(Serving.allowed?([["a"]], '["a"]')).to be(false) From ba134bd50d4c206891a53d397523230bd38e6913 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 1 Dec 2026 10:34:19 +0000 Subject: [PATCH 08/15] fix: configurable X-Application-Version, sent only as a whole number 1.4.0 hardcoded X-Application-Version to 0 with no way to set it. Add application_version to ClientConfig (attribute, keyword, properties), Absmartly.configure_client and ABSmartly.new; the client sends it when it is a whole number of 1-18 digits and 0 otherwise, as java-sdk Client applicationVersionHeader and javascript-sdk client.ts do. Regression specs cover every entry point, the header on fetch and publish, accepted and rejected values, a config object without the reader, and that it never becomes an audience attribute. README and CHANGELOG updated. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +- README.md | 2 + lib/a_b_smartly.rb | 6 +- lib/absmartly.rb | 3 +- lib/client.rb | 25 +++++- lib/client_config.rb | 7 +- spec/client_application_version_spec.rb | 115 ++++++++++++++++++++++++ 7 files changed, 155 insertions(+), 7 deletions(-) create mode 100644 spec/client_application_version_spec.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index a7411064..1208ba44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,10 @@ ## [1.5.0] - Unreleased -Adds switchback experiments on top of 1.4.0, without breaking it: every 1.4.0 class, method signature, return value, error and behaviour is kept, and experiments that are not switchbacks are assigned, exposed and published as in 1.4.0. Only the timestamps and two unit-hashing cases change, as each Fixed entry says. +Adds switchback experiments on top of 1.4.0, without breaking it: every 1.4.0 class, method signature, return value, error and behaviour is kept, and experiments that are not switchbacks are assigned, exposed and published as in 1.4.0. Only the timestamps, two unit-hashing cases and the `X-Application-Version` header change, as each Fixed entry says. ### Added - Switchback experiments, served as the Collector and the Java SDK serve them (the R33 cluster-defined contract). An experiment with `randomizationType: "switchback"` lists in `switchbackClusters`, in order, the unit types it is linked to and the attribute path holding each one's cluster value (`/` nests, a quoted segment is a literal key, an integer segment indexes an array). The first linked unit, in declared order, whose attribute gives a value serves the experiment and its exposure; the value is the cluster key, used raw (never hashed): a non-empty String as is, an Integer as its decimal text, while a Float (`3.0` included), boolean, Hash, Array, `""` or `nil` gives none. The variant is the platform's balanced-block draw for the period `floor((now - switchbackStartAt) / switchbackPeriodMs)` and the experiment's 64-bit seed. No value, disagreeing units or a value outside `switchbackClusterValues` give control and no exposure. That allow-list matches String entries as is and Integer (and boolean) entries by their decimal text (`17` admits `"17"`); switchbacks do not support floats, so a Float entry (`2.5`, `3.0`) never matches any cluster key; so do the time before `switchbackStartAt` and an unservable schedule (a start that is not hour aligned, a period of 0 or less, fewer than two arms), where rules, a strict audience and full-on still apply. Overrides, assignment rules (a split rule over the serving unit), strict audiences, full-on, traffic (on the serving unit) and custom assignments apply in the Collector's order; holdouts never apply to a switchback. One exposure is sent per experiment and period while its assignment is unchanged (a custom assignment, override or refresh that rebuilds it within the period, or a clock that returns to a period no longer among the two most recent, sends one more), stamped with the time that chose the period, and the cluster value is read once per period. Changing a unit's cluster attribute mid-period, before its exposure, is not supported: callers set it before the first read, and a change takes effect in the next period. A period keeps a copy of the cluster-source attribute values it read (a String, Array or Hash, to the depth a path reads), so changing a value passed to `set_attribute` in place does not change the cluster it served or the attributes its own exposure request carries; other attributes are not copied, and an in-place change to a key of an identity-compared Hash is not supported. The Collector resolves the serving unit and cluster again from the published units and attributes at `exposedAt`, so a switchback exposure that the batch would credit to another unit or cluster (an attribute changed within the period, a unit set afterwards, a write in the exposure's millisecond, a clock that stepped back) is published in a request of its own, with the units and attributes its period read and its own `exposedAt`; `publish` then sends more than one request. A string cluster value keys by its published UTF-8 text. The new experiment fields (`randomization_type`, `switchback_clusters`, `switchback_cluster_values`, `switchback_start_at`, `switchback_period_ms`, `switchback_carryover_duration_ms`, `switchback_burn_in_duration_ms`, `switchback_burn_out_duration_ms`, `switchback_design_type`, `switchback_estimand`) are optional; payloads without switchbacks assign, expose and publish as in 1.4.0 (one request per `publish`) and read no extra clock to do so. +- `application_version` on `ClientConfig` (also `ClientConfig.new(application_version:)`, the `application_version` property in `create_from_properties`), on `Absmartly.configure_client`, and as an `ABSmartly.new` keyword option; `Client#application_version` returns the value sent. See Fixed. ### Changed - Experiments with `randomizationType: "switchback"` are served as switchbacks. 1.4.0 served a switchback that has a `unitType` as an ordinary experiment on that unit (a sticky variant that ignores clusters and periods). Who moves: units in running switchback experiments, which move to their cluster's schedule; their exposures move to the serving unit and to one per period while the assignment is unchanged. @@ -11,6 +12,7 @@ Adds switchback experiments on top of 1.4.0, without breaking it: every 1.4.0 cl - The `X-Agent` header is now `absmartly-ruby-sdk/1.5.0`. ### Fixed +- `X-Application-Version` is no longer always `0`: 1.4.0 hardcoded it, with no way to configure it. The configured `application_version` (see Added) is sent when it is a whole number of 1 to 18 digits (an Integer, an integral Float, or a String with surrounding spaces trimmed), and `0` otherwise (`nil`, `"2.4.1"`, a negative number), as the Java and JavaScript SDKs send it; the collector rejects any other value. Who is affected: nobody, unless they configure a version; applications that set one now get it recorded with their events. It is not an audience or rule attribute and is not added to the published attributes. - Every timestamp the SDK sends (`publishedAt`, `exposedAt`, `setAt`, `achievedAt`) is the current time in epoch milliseconds, as the Collector reads it and the JavaScript and Java SDKs send it. Up to 1.4.0 they were the context's creation time in seconds, so every event looked more than 50 years old and stayed at one instant for the context's life. Contexts made by `ABSmartly#create_context`, `create_context_async` and `create_context_with` read a millisecond clock on every call; a `Time` passed to `Context.create` is still one fixed instant, now in milliseconds, and a callable clock (`-> { millis }`) is read on each call. `publishedAt` is never earlier than an event in its batch, so a wall clock that steps back does not get the batch rejected. Who is affected: every published event changes its timestamps (not its content); collectors, proxies and tests that read or compared those values in seconds see milliseconds. - Float unit UIDs are hashed from the text JavaScript's `toFixed(0)` gives (`1.5` as `"2"`, `125.75` as `"126"`, `-0.0` as `"0"`, `-0.4` as `"-0"`, `1e21` as `"1e+21"`), as the JavaScript and Java SDKs and the Collector hash them; 1.4.0 hashed `Float#to_s` (`"1.5"`). Integer (exact decimal text, beyond 2**53 too), BigDecimal and Rational UIDs and UTF-8 strings hash as in 1.4.0. Who is affected: units set with a Float UID; they are reassigned once (they may get another variant) and exposed again, and from then on match every other SDK. - Unit UIDs in another encoding than UTF-8 (e.g. UTF-16) are transcoded to UTF-8 before hashing, a surrogate pair written as CESU-8 bytes is joined, and a lone surrogate or invalid byte becomes U+FFFD, as the JavaScript SDK's `TextEncoder` encodes them; 1.4.0 hashed the string's own bytes. Who is affected: units set with a non-UTF-8 String UID, or a UTF-8 String holding CESU-8 surrogates or invalid bytes; they are reassigned once and exposed again, and from then on match every other SDK. `get_unit` still returns the UID as set. diff --git a/README.md b/README.md index 0dab14a8..5780a5ca 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,7 @@ client_config.endpoint = "https://your-company.absmartly.io/v1" client_config.api_key = "YOUR-API-KEY" client_config.application = "website" client_config.environment = "development" +client_config.application_version = 1_000_003 # optional; a whole number, sent as X-Application-Version client_config.connect_timeout = 3.0 client_config.connection_request_timeout = 3.0 client_config.retry_interval = 0.5 @@ -111,6 +112,7 @@ sdk = ABSmartly.create(sdk_config) | timeout | `Integer` | ❌ | `3000` | The connection and request timeout in milliseconds. Converted to seconds internally. | | retries | `Integer` | ❌ | `5` | The maximum number of retries before giving up. | | context_event_logger | `ContextEventLogger` | ❌ | `nil` | A `ContextEventLogger` instance implementing `handle_event(event, data)` to receive SDK events. See "Custom Event Logger" below. | +| application_version | `Integer` or `String` | ❌ | `nil` | Your application's version, sent as the `X-Application-Version` header. The collector only accepts a whole number, so a value of 1 to 18 digits (e.g. `1000003` or `"1000003"`) is sent as is and anything else (`nil`, `"2.4.1"`) as `0`. Also `config.application_version` with `Absmartly.configure_client` or `ClientConfig`. | ## Creating a New Context diff --git a/lib/a_b_smartly.rb b/lib/a_b_smartly.rb index 637ca165..8ddb768a 100644 --- a/lib/a_b_smartly.rb +++ b/lib/a_b_smartly.rb @@ -23,7 +23,7 @@ def self.create(config) ABSmartly.new(config) end - OPTIONS = %i[api_key application environment timeout retries context_event_logger].freeze + OPTIONS = %i[api_key application environment timeout retries context_event_logger application_version].freeze # Accepts either a config object (ABSmartlyConfig or anything that responds # like it) or an endpoint String with keyword options. Options are read from @@ -80,7 +80,8 @@ def initialize_from_config(config) end end - def initialize_from_params(endpoint, api_key, application, environment, timeout, retries, event_logger) + def initialize_from_params(endpoint, api_key, application, environment, timeout, retries, event_logger, + application_version = nil) raise ArgumentError.new("Missing required parameter: endpoint") if endpoint.nil? || endpoint.to_s.strip.empty? raise ArgumentError.new("Missing required parameter: api_key") if api_key.nil? || api_key.to_s.strip.empty? raise ArgumentError.new("Missing required parameter: application") if application.nil? || application.to_s.strip.empty? @@ -100,6 +101,7 @@ def initialize_from_params(endpoint, api_key, application, environment, timeout, client_config.connect_timeout = timeout / 1000.0 client_config.connection_request_timeout = timeout / 1000.0 client_config.max_retries = retries + client_config.application_version = application_version @client = Client.create(client_config) @context_data_provider = DefaultContextDataProvider.new(@client) diff --git a/lib/absmartly.rb b/lib/absmartly.rb index f1762686..8a8379b7 100644 --- a/lib/absmartly.rb +++ b/lib/absmartly.rb @@ -14,7 +14,7 @@ class Error < StandardError class << self attr_accessor :endpoint, :api_key, :application, :environment, :connect_timeout, :connection_request_timeout, :retry_interval, :max_retries, - :event_logger + :event_logger, :application_version def configure_client yield self @@ -51,6 +51,7 @@ def client_config @client_config.api_key = @api_key @client_config.application = @application @client_config.environment = @environment + @client_config.application_version = @application_version @client_config.connect_timeout = @connect_timeout @client_config.connection_request_timeout = @connection_request_timeout @client_config.retry_interval = @retry_interval diff --git a/lib/client.rb b/lib/client.rb index cd0231ce..c3aba700 100644 --- a/lib/client.rb +++ b/lib/client.rb @@ -10,6 +10,25 @@ class Client attr_accessor :url, :query, :headers, :http_client, :executor, :deserializer, :serializer attr_reader :data_future, :promise, :exception, :application, :environment + # The X-Application-Version value sent (see application_version_header). + attr_reader :application_version + + # The collector reads X-Application-Version as a 64-bit integer and rejects + # any other value, so only a whole number of 1 to 18 digits is sent as is + # (an Integer, an integral Float as JavaScript's number text, or a String + # with surrounding spaces trimmed); anything else (nil, "2.4.1", -1, 1.5) is + # sent as "0", as the Java and JavaScript SDKs do. + APPLICATION_VERSION = /\A[0-9]{1,18}\z/.freeze + private_constant :APPLICATION_VERSION + + def self.application_version_header(version) + text = case version + when Integer then version.to_s + when Float then version.to_i.to_s if version.finite? && version == version.floor + when String then version.strip + end + !text.nil? && APPLICATION_VERSION.match?(text) ? text : "0" + end def self.create(config, http_client = nil) Client.new(config, http_client || DefaultHttpClient.create(config.http_client_config)) @@ -32,6 +51,10 @@ def initialize(config, http_client = nil) @http_client = http_client @application = application @environment = environment + # A config written before application_version existed may not define it. + @application_version = Client.application_version_header( + config.respond_to?(:application_version) ? config.application_version : nil + ) @deserializer = config.context_data_deserializer @serializer = config.context_event_serializer @executor = config.executor @@ -44,7 +67,7 @@ def initialize(config, http_client = nil) "X-API-Key": api_key, "X-Application": application, "X-Environment": environment, - "X-Application-Version": "0", + "X-Application-Version": @application_version, "X-Agent": "absmartly-ruby-sdk/#{Absmartly::VERSION}" } diff --git a/lib/client_config.rb b/lib/client_config.rb index 90c7821b..36941516 100644 --- a/lib/client_config.rb +++ b/lib/client_config.rb @@ -5,7 +5,8 @@ class ClientConfig attr_accessor :endpoint, :api_key, :environment, :application, :deserializer, :serializer, :executor, :connect_timeout, :connection_request_timeout, - :retry_interval, :max_retries, :retry_statuses, :retry_connection_failures + :retry_interval, :max_retries, :retry_statuses, :retry_connection_failures, + :application_version def self.create ClientConfig.new @@ -18,14 +19,16 @@ def self.create_from_properties(properties, prefix) client_config.environment = properties["#{prefix}environment".to_sym] client_config.application = properties["#{prefix}application".to_sym] client_config.api_key = properties["#{prefix}apikey".to_sym] + client_config.application_version = properties["#{prefix}application_version".to_sym] client_config end - def initialize(endpoint: nil, environment: nil, application: nil, api_key: nil) + def initialize(endpoint: nil, environment: nil, application: nil, api_key: nil, application_version: nil) @endpoint = endpoint @environment = environment @application = application @api_key = api_key + @application_version = application_version end def context_data_deserializer diff --git a/spec/client_application_version_spec.rb b/spec/client_application_version_spec.rb new file mode 100644 index 00000000..b649f786 --- /dev/null +++ b/spec/client_application_version_spec.rb @@ -0,0 +1,115 @@ +# frozen_string_literal: true + +require "absmartly" + +# X-Application-Version: the configured application version, sent only when it +# is a whole number of 1 to 18 digits, otherwise "0" (java-sdk Client +# applicationVersionHeader, javascript-sdk client.ts applicationVersionHeader). +RSpec.describe "Client application version" do + def client_config(version = :unset) + config = ClientConfig.create + config.endpoint = "https://localhost/v1" + config.api_key = "test-api-key" + config.application = "website" + config.environment = "dev" + config.application_version = version unless version == :unset + config + end + + def header(version) + Client.create(client_config(version), instance_double(DefaultHttpClient)).headers[:"X-Application-Version"] + end + + it "sends 0 when no version is configured, as 1.4.0 did" do + expect(Client.create(client_config, instance_double(DefaultHttpClient)).headers[:"X-Application-Version"]).to eq("0") + expect(header(nil)).to eq("0") + end + + it "sends a whole number of 1 to 18 digits as is" do + { + 1_000_003 => "1000003", "1000003" => "1000003", " 42 " => "42", 0 => "0", "007" => "007", + "999999999999999999" => "999999999999999999", 999_999_999_999_999_999 => "999999999999999999", + 3.0 => "3" + }.each { |version, sent| expect(header(version)).to eq(sent), version.inspect } + end + + it "sends 0 for anything else" do + ["2.4.1", "1.0", "", " ", "-1", -1, "+1", "1e3", "12a", "1_000", "١", "1\n2", + "1000000000000000000", 1_000_000_000_000_000_000, 1.5, -2.0, Float::NAN, Float::INFINITY, + :"123", ["1"], { v: 1 }, true].each do |version| + expect(header(version)).to eq("0"), version.inspect + end + end + + it "sends the header on both the context fetch and the publish" do + http_client = instance_double(DefaultHttpClient) + client = Client.create(client_config("1000003"), http_client) + seen = [] + response = OpenStruct.new(success?: true, body: '{"experiments":[]}', status: 200) + allow(http_client).to receive(:get) { |_url, _query, headers| seen << headers[:"X-Application-Version"]; response } + allow(http_client).to receive(:put) { |_url, _query, headers, _body| seen << headers[:"X-Application-Version"]; response } + client.context_data + event = PublishEvent.new + event.hashed = true + event.published_at = 1 + event.units = [] + client.publish(event) + expect(seen).to eq(%w[1000003 1000003]) + end + + it "is configurable through every client entry point" do + sdk = ABSmartly.new("https://localhost/v1", api_key: "k", application: "website", environment: "dev", + application_version: 1_000_003) + expect(sdk.client.headers[:"X-Application-Version"]).to eq("1000003") + expect(sdk.client.application_version).to eq("1000003") + + props = { "absmartly.endpoint": "https://localhost/v1", "absmartly.environment": "dev", + "absmartly.apikey": "k", "absmartly.application": "website", + "absmartly.application_version": "77" } + config = ClientConfig.create_from_properties(props, "absmartly.") + expect(config.application_version).to eq("77") + expect(Client.create(config, instance_double(DefaultHttpClient)).headers[:"X-Application-Version"]).to eq("77") + + keyword = ClientConfig.new(endpoint: "https://localhost/v1", environment: "dev", application: "website", + api_key: "k", application_version: "88") + expect(Client.create(keyword, instance_double(DefaultHttpClient)).headers[:"X-Application-Version"]).to eq("88") + + Absmartly.configure_client do |c| + c.endpoint = "https://localhost/v1" + c.api_key = "k" + c.application = "website" + c.environment = "dev" + c.application_version = "99" + end + expect(Absmartly.send(:client_config).application_version).to eq("99") + ensure + Absmartly.application_version = nil + end + + # A config object written for 1.4.0 has no application_version reader. + it "accepts a client config without an application_version reader" do + legacy = Struct.new(:endpoint, :api_key, :application, :environment, :context_data_deserializer, + :context_event_serializer, :executor) + .new("https://localhost/v1", "k", "website", "dev", nil, nil, nil) + expect(Client.new(legacy, instance_double(DefaultHttpClient)).headers[:"X-Application-Version"]).to eq("0") + end + + it "is accepted as a keyword option of ABSmartly.new" do + expect(ABSmartly::OPTIONS).to include(:application_version) + expect { ABSmartly.new("https://localhost/v1", api_key: "k", application: "website", environment: "dev", + application_version: "2.4.1") }.not_to raise_error + end + + # Only the header carries it: audiences and rule conditions never see an app_version or + # application_version attribute, and nothing is added to the published attributes. + it "is not an audience attribute" do + sdk = ABSmartly.new("https://localhost/v1", api_key: "k", application: "website", environment: "dev", + application_version: 1_000_003) + json = '{"experiments":[]}' + data = DefaultContextDataDeserializer.new.deserialize(json, 0, json.length) + context = sdk.create_context_with(ContextConfig.create, Absmartly::ContextDataResult.new(data)) + keys = context.send(:evaluator_attributes).keys.map(&:to_s) + expect(keys).not_to include("app_version", "application_version") + expect(context.get_attributes).to eq({}) + end +end From 44e06d79601bc4eabf9fc8f45646de367d0db8e5 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 1 Dec 2026 11:12:28 +0000 Subject: [PATCH 09/15] feat: contains operator, an alias of in; fix lint, binary ids, big-float version - JSON expressions: `contains` is registered as the same InOperator object as `in` ([haystack, needle]); `in` is unchanged. Specs run every in case through contains (value, boolean and variable paths, malformed operands). CHANGELOG Added line and README. - Review (ba134bd) P2: RuboCop Layout/EndAlignment in Client.application_version_header. - Review P2: a binary string that is not UTF-8 text keeps 1.4.0's raw-byte hash, so byte ids differing in one byte no longer share a bucket; binary UTF-8 text (CESU-8 pairs and lone surrogates included) still hashes as text. Regression: 2,000 one-byte-apart 16-byte ids all hash apart. - Review P3: an integral Float application_version is sent as JavaScript's String(number) (2**56 as 72057594037927940). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +- README.md | 2 +- lib/client.rb | 13 +++-- lib/hashing.rb | 14 ++++- lib/json_expr/json_expr.rb | 6 +- spec/client_application_version_spec.rb | 4 +- spec/json_expr/contains_operator_spec.rb | 73 ++++++++++++++++++++++++ spec/parity_spec.rb | 18 ++++++ 8 files changed, 123 insertions(+), 10 deletions(-) create mode 100644 spec/json_expr/contains_operator_spec.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 1208ba44..be02c375 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ Adds switchback experiments on top of 1.4.0, without breaking it: every 1.4.0 cl ### Added - Switchback experiments, served as the Collector and the Java SDK serve them (the R33 cluster-defined contract). An experiment with `randomizationType: "switchback"` lists in `switchbackClusters`, in order, the unit types it is linked to and the attribute path holding each one's cluster value (`/` nests, a quoted segment is a literal key, an integer segment indexes an array). The first linked unit, in declared order, whose attribute gives a value serves the experiment and its exposure; the value is the cluster key, used raw (never hashed): a non-empty String as is, an Integer as its decimal text, while a Float (`3.0` included), boolean, Hash, Array, `""` or `nil` gives none. The variant is the platform's balanced-block draw for the period `floor((now - switchbackStartAt) / switchbackPeriodMs)` and the experiment's 64-bit seed. No value, disagreeing units or a value outside `switchbackClusterValues` give control and no exposure. That allow-list matches String entries as is and Integer (and boolean) entries by their decimal text (`17` admits `"17"`); switchbacks do not support floats, so a Float entry (`2.5`, `3.0`) never matches any cluster key; so do the time before `switchbackStartAt` and an unservable schedule (a start that is not hour aligned, a period of 0 or less, fewer than two arms), where rules, a strict audience and full-on still apply. Overrides, assignment rules (a split rule over the serving unit), strict audiences, full-on, traffic (on the serving unit) and custom assignments apply in the Collector's order; holdouts never apply to a switchback. One exposure is sent per experiment and period while its assignment is unchanged (a custom assignment, override or refresh that rebuilds it within the period, or a clock that returns to a period no longer among the two most recent, sends one more), stamped with the time that chose the period, and the cluster value is read once per period. Changing a unit's cluster attribute mid-period, before its exposure, is not supported: callers set it before the first read, and a change takes effect in the next period. A period keeps a copy of the cluster-source attribute values it read (a String, Array or Hash, to the depth a path reads), so changing a value passed to `set_attribute` in place does not change the cluster it served or the attributes its own exposure request carries; other attributes are not copied, and an in-place change to a key of an identity-compared Hash is not supported. The Collector resolves the serving unit and cluster again from the published units and attributes at `exposedAt`, so a switchback exposure that the batch would credit to another unit or cluster (an attribute changed within the period, a unit set afterwards, a write in the exposure's millisecond, a clock that stepped back) is published in a request of its own, with the units and attributes its period read and its own `exposedAt`; `publish` then sends more than one request. A string cluster value keys by its published UTF-8 text. The new experiment fields (`randomization_type`, `switchback_clusters`, `switchback_cluster_values`, `switchback_start_at`, `switchback_period_ms`, `switchback_carryover_duration_ms`, `switchback_burn_in_duration_ms`, `switchback_burn_out_duration_ms`, `switchback_design_type`, `switchback_estimand`) are optional; payloads without switchbacks assign, expose and publish as in 1.4.0 (one request per `publish`) and read no extra clock to do so. +- A `contains` operator for audience filters and assignment rule conditions, an alias of `in`, so the app can start sending `contains`: the same `[haystack, needle]` operands and the same result in every case (list membership, substring of a string, key of an object, `null` otherwise). `in` is unchanged. - `application_version` on `ClientConfig` (also `ClientConfig.new(application_version:)`, the `application_version` property in `create_from_properties`), on `Absmartly.configure_client`, and as an `ABSmartly.new` keyword option; `Client#application_version` returns the value sent. See Fixed. ### Changed @@ -15,7 +16,7 @@ Adds switchback experiments on top of 1.4.0, without breaking it: every 1.4.0 cl - `X-Application-Version` is no longer always `0`: 1.4.0 hardcoded it, with no way to configure it. The configured `application_version` (see Added) is sent when it is a whole number of 1 to 18 digits (an Integer, an integral Float, or a String with surrounding spaces trimmed), and `0` otherwise (`nil`, `"2.4.1"`, a negative number), as the Java and JavaScript SDKs send it; the collector rejects any other value. Who is affected: nobody, unless they configure a version; applications that set one now get it recorded with their events. It is not an audience or rule attribute and is not added to the published attributes. - Every timestamp the SDK sends (`publishedAt`, `exposedAt`, `setAt`, `achievedAt`) is the current time in epoch milliseconds, as the Collector reads it and the JavaScript and Java SDKs send it. Up to 1.4.0 they were the context's creation time in seconds, so every event looked more than 50 years old and stayed at one instant for the context's life. Contexts made by `ABSmartly#create_context`, `create_context_async` and `create_context_with` read a millisecond clock on every call; a `Time` passed to `Context.create` is still one fixed instant, now in milliseconds, and a callable clock (`-> { millis }`) is read on each call. `publishedAt` is never earlier than an event in its batch, so a wall clock that steps back does not get the batch rejected. Who is affected: every published event changes its timestamps (not its content); collectors, proxies and tests that read or compared those values in seconds see milliseconds. - Float unit UIDs are hashed from the text JavaScript's `toFixed(0)` gives (`1.5` as `"2"`, `125.75` as `"126"`, `-0.0` as `"0"`, `-0.4` as `"-0"`, `1e21` as `"1e+21"`), as the JavaScript and Java SDKs and the Collector hash them; 1.4.0 hashed `Float#to_s` (`"1.5"`). Integer (exact decimal text, beyond 2**53 too), BigDecimal and Rational UIDs and UTF-8 strings hash as in 1.4.0. Who is affected: units set with a Float UID; they are reassigned once (they may get another variant) and exposed again, and from then on match every other SDK. -- Unit UIDs in another encoding than UTF-8 (e.g. UTF-16) are transcoded to UTF-8 before hashing, a surrogate pair written as CESU-8 bytes is joined, and a lone surrogate or invalid byte becomes U+FFFD, as the JavaScript SDK's `TextEncoder` encodes them; 1.4.0 hashed the string's own bytes. Who is affected: units set with a non-UTF-8 String UID, or a UTF-8 String holding CESU-8 surrogates or invalid bytes; they are reassigned once and exposed again, and from then on match every other SDK. `get_unit` still returns the UID as set. +- Unit UIDs in another encoding than UTF-8 (e.g. UTF-16) are transcoded to UTF-8 before hashing, a surrogate pair written as CESU-8 bytes is joined, and a lone surrogate or invalid byte becomes U+FFFD, as the JavaScript SDK's `TextEncoder` encodes them; 1.4.0 hashed the string's own bytes. A binary (`ASCII-8BIT`) string that holds UTF-8 text is hashed as that text; one that is not text (raw bytes such as a `BINARY(16)` id or a digest) keeps 1.4.0's raw-byte hash, so ids that differ in a byte never share a bucket. Who is affected: units set with a non-UTF-8 String UID, or a UTF-8 String holding CESU-8 surrogates or invalid bytes; they are reassigned once and exposed again, and from then on match every other SDK. `get_unit` still returns the UID as set. ## [1.4.0] - 2026-11-17 diff --git a/README.md b/README.md index 5780a5ca..c42f314c 100644 --- a/README.md +++ b/README.md @@ -320,7 +320,7 @@ Experiments can define assignment rules on the Web Console. They are evaluated i - An `assign` rule gives a fixed variant. - A `split` rule randomizes the unit over its own percentages, e.g. `20/30/50`. While the experiment's unit is missing, it gives the full-on variant (0 for an experiment that is not full-on); once the unit is set, the rule is re-resolved unless that variant was already exposed. -Rule conditions are audience expressions, so they can use your attributes, `application`, `environment` and the `semver_eq`, `semver_gt`, `semver_gte`, `semver_lt` and `semver_lte` operators, e.g. `{"semver_gte": [{"var": "app_version"}, {"value": "2.4.0"}]}`. +Rule conditions are audience expressions, so they can use your attributes, `application`, `environment` and the `semver_eq`, `semver_gt`, `semver_gte`, `semver_lt` and `semver_lte` operators, e.g. `{"semver_gte": [{"var": "app_version"}, {"value": "2.4.0"}]}`. `contains` is an alias of `in` (`[haystack, needle]`: list membership, a substring of a string, a key of an object), e.g. `{"contains": [{"var": "tags"}, {"value": "beta"}]}`. ### Holdouts diff --git a/lib/client.rb b/lib/client.rb index c3aba700..8259184b 100644 --- a/lib/client.rb +++ b/lib/client.rb @@ -22,11 +22,14 @@ class Client private_constant :APPLICATION_VERSION def self.application_version_header(version) - text = case version - when Integer then version.to_s - when Float then version.to_i.to_s if version.finite? && version == version.floor - when String then version.strip - end + text = + case version + when Integer then version.to_s + # JavaScript's String(number): the shortest round-trip digits, so 2**56 + # is "72057594037927940" as the JavaScript SDK sends it. + when Float then version.to_s.to_r.to_i.to_s if version.finite? && version == version.floor + when String then version.strip + end !text.nil? && APPLICATION_VERSION.match?(text) ? text : "0" end diff --git a/lib/hashing.rb b/lib/hashing.rb index ea03be58..7086d680 100644 --- a/lib/hashing.rb +++ b/lib/hashing.rb @@ -49,11 +49,15 @@ def self.base64_url_no_padding(bytes) # BMP become the standard 4-byte sequence and each lone surrogate becomes # U+FFFD, matching the JavaScript SDK's TextEncoder-based encoding. Strings in # another encoding (e.g. UTF-16) are transcoded; binary strings are read as - # UTF-8 bytes. + # UTF-8 bytes. A binary string that is not UTF-8 text even after joining + # CESU-8 pairs (raw bytes such as a BINARY(16) id or a digest) is hashed + # from its own bytes, as in 1.4.0: replacing each invalid byte with U+FFFD + # would give distinct byte ids one hash. def self.to_utf8(value) str = value.to_s if str.encoding == Encoding::UTF_8 || str.encoding == Encoding::BINARY || str.encoding == Encoding::US_ASCII return str if str.encoding == Encoding::UTF_8 && str.valid_encoding? + return str.b if str.encoding == Encoding::BINARY && !utf8_text?(str) bytes = str.b bytes = bytes.gsub(ENCODED_SURROGATE_PAIR) do @@ -67,4 +71,12 @@ def self.to_utf8(value) str.encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: REPLACEMENT) end end + + # Whether binary bytes are UTF-8 text once CESU-8 surrogate pairs are + # joined (a lone surrogate counts as text, as JavaScript would encode it). + def self.utf8_text?(bytes) + joined = bytes.b.gsub(ENCODED_SURROGATE_PAIR, "\u{FFFD}".b).gsub(ENCODED_SURROGATE, "\u{FFFD}".b) + joined.force_encoding(Encoding::UTF_8).valid_encoding? + end + private_class_method :utf8_text? end diff --git a/lib/json_expr/json_expr.rb b/lib/json_expr/json_expr.rb index d58ee323..5c7a7a89 100644 --- a/lib/json_expr/json_expr.rb +++ b/lib/json_expr/json_expr.rb @@ -24,6 +24,7 @@ class JsonExpr attr_accessor :vars def initialize + in_operator = InOperator.new @operators = { "and": AndCombinator.new, "or": OrCombinator.new, @@ -31,7 +32,10 @@ def initialize "var": VarOperator.new, "null": NilOperator.new, "not": NotOperator.new, - "in": InOperator.new, + "in": in_operator, + # The same operator under the name the other SDKs and the app use: + # [haystack, needle], identical to "in" in every case. + "contains": in_operator, "match": MatchOperator.new, "eq": EqualsOperator.new, "gt": GreaterThanOperator.new, diff --git a/spec/client_application_version_spec.rb b/spec/client_application_version_spec.rb index b649f786..1531bbae 100644 --- a/spec/client_application_version_spec.rb +++ b/spec/client_application_version_spec.rb @@ -29,7 +29,9 @@ def header(version) { 1_000_003 => "1000003", "1000003" => "1000003", " 42 " => "42", 0 => "0", "007" => "007", "999999999999999999" => "999999999999999999", 999_999_999_999_999_999 => "999999999999999999", - 3.0 => "3" + 3.0 => "3", + # JavaScript's String(2 ** 56) is "72057594037927940". + 2.0**56 => "72057594037927940" }.each { |version, sent| expect(header(version)).to eq(sent), version.inspect } end diff --git a/spec/json_expr/contains_operator_spec.rb b/spec/json_expr/contains_operator_spec.rb new file mode 100644 index 00000000..06d5f09f --- /dev/null +++ b/spec/json_expr/contains_operator_spec.rb @@ -0,0 +1,73 @@ +# frozen_string_literal: true + +require "json_expr/json_expr" + +# `contains` is the `in` operator under another name: the same [haystack, needle] operands, the +# same list membership (through the evaluator's compare), substring, map-key and null results. +RSpec.describe "contains operator" do + let(:expr) { JsonExpr.new } + + def value(v) + { value: v } + end + + # [haystack, needle, vars], covering every case of the in operator specs. + CASES = [ + # String haystack: substring of the needle's string form. + ["abcdefghijk", "abc"], ["abcdefghijk", "def"], ["abcdefghijk", "xxx"], ["abcdefghijk", nil], + [nil, "abc"], ["abc1", 1], ["abc", [1]], ["", ""], ["true", true], ["1.5", 1.5], + # Array haystack: membership through the evaluator's compare. + [[], 1], [[], "1"], [[], true], [[], false], [[], nil], [[0, 1], 2], [[1, 2], 0], [[1, 2], 1], + [[1, 2], 2], [%w[1 2], 1], [[1, 2], "1"], [[true], true], [[nil], nil], [[[1]], [1]], [["a"], "A"], + # Map haystack: key of the needle's string form, String or Symbol. + [{ "a" => 1, "b" => 2 }, "c"], [{ "b" => 2, "c" => 3, "0" => 100 }, "a"], + [{ "b" => 2, "c" => 3, "0" => 100 }, "b"], [{ "b" => 2, "c" => 3, "0" => 100 }, "c"], + [{ "b" => 2, "c" => 3, "0" => 100 }, 0], [{ "a" => 1 }, nil], + # Any other haystack: null. + [5, 1], [true, true], [1.5, 1] + ].freeze + + it "returns what in returns for every haystack and needle" do + CASES.each do |haystack, needle| + via_in = expr.evaluate_expr({ in: [value(haystack), value(needle)] }, {}) + via_contains = expr.evaluate_expr({ contains: [value(haystack), value(needle)] }, {}) + expect(via_contains).to eq(via_in), [haystack, needle].inspect + end + end + + it "reads map keys from variables, symbolized audience attributes included" do + vars = { h: { a: 1 } } + [["a", true], ["b", false]].each do |needle, expected| + expect(expr.evaluate_expr({ contains: [{ var: "h" }, value(needle)] }, vars)).to be(expected) + expect(expr.evaluate_expr({ in: [{ var: "h" }, value(needle)] }, vars)).to be(expected) + end + end + + it "is haystack first, as in is" do + expect(expr.evaluate_expr({ contains: [value("abc1"), value(1)] }, {})).to be(true) + expect(expr.evaluate_expr({ contains: [value(1), value("abc1")] }, {})).to be_nil + expect(expr.evaluate_expr({ contains: [value(%w[a b]), value("a")] }, {})).to be(true) + expect(expr.evaluate_expr({ contains: [value("a"), value(%w[a b])] }, {})).to be(false) + end + + it "evaluates as a boolean audience filter exactly like in" do + CASES.each do |haystack, needle| + via_in = expr.evaluate_boolean_expr({ in: [value(haystack), value(needle)] }, {}) + via_contains = expr.evaluate_boolean_expr({ contains: [value(haystack), value(needle)] }, {}) + expect(via_contains).to eq(via_in), [haystack, needle].inspect + end + end + + it "keeps in unchanged and maps contains to the same operator" do + expect(expr.operators[:in]).to be_a(InOperator) + expect(expr.operators[:contains]).to equal(expr.operators[:in]) + end + + # A null or missing operand list gives null for both names. + it "gives null for malformed operands, as in does" do + [nil, [], [value("a")], "x"].each do |operands| + expect(expr.evaluate_expr({ contains: operands }, {})).to eq(expr.evaluate_expr({ in: operands }, {})), + operands.inspect + end + end +end diff --git a/spec/parity_spec.rb b/spec/parity_spec.rb index 607f9c56..44b2ca95 100644 --- a/spec/parity_spec.rb +++ b/spec/parity_spec.rb @@ -64,6 +64,24 @@ expect(Hashing.hash_unit(wtf8)).to eq(lone_surrogate_hash) end + # Raw binary ids (a BINARY(16) column, a digest) are not text: they keep 1.4.0's raw-byte hash, + # so ids that differ in one byte never share a bucket. + it "hashes binary bytes that are not UTF-8 text from their own bytes" do + a = "\xFF\xFE\x01".b + b = "\xFE\xFF\x01".b + expect(Hashing.hash_unit(a)).to eq(Hashing.base64_url_no_padding(Digest::MD5.digest(a))) + expect(Hashing.hash_unit(a)).not_to eq(Hashing.hash_unit(b)) + rng = Random.new(7) + 2_000.times do + x = rng.bytes(16).b + y = x.dup + y.setbyte(5, (y.getbyte(5) + 1) % 256) + expect(Hashing.hash_unit(x)).not_to eq(Hashing.hash_unit(y)), x.unpack1("H*") + end + # A lone surrogate written as bytes is still text, as JavaScript encodes it. + expect(Hashing.hash_unit("ab\xED\xA0\xBDcd".b)).to eq(lone_surrogate_hash) + end + # Text tagged US-ASCII or binary is read as its UTF-8 bytes, CESU-8 pairs included. it "hashes US-ASCII- and binary-tagged bytes as the UTF-8 text they hold" do expect(Hashing.hash_unit("\xC3\xA9".dup.force_encoding("US-ASCII"))).to eq(Hashing.hash_unit("\u00E9")) From ad23e5a020ad1f92129a1a8392f3246468030702 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 1 Dec 2026 11:59:26 +0000 Subject: [PATCH 10/15] fix: hash raw US-ASCII-tagged bytes as in 1.4.0; scope the contains note Review (44e06d7) P3s: - A US-ASCII-tagged string that is not UTF-8 text keeps 1.4.0's raw-byte hash, as a binary one does, so byte ids one byte apart never share a bucket. Regression in parity_spec. - contains: the comment and CHANGELOG name the SDKs that have it (Elixir, C++, Rust, Scala) and say to send it only once every SDK in use understands it (Ruby <= 1.4.0, JS 1.14.1 and Java 1.10.0 evaluate it to null). - README install hint ~> 1.5. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++-- lib/hashing.rb | 10 +++++----- lib/json_expr/json_expr.rb | 4 ++-- spec/parity_spec.rb | 5 +++++ 4 files changed, 14 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index be02c375..d338da69 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ Adds switchback experiments on top of 1.4.0, without breaking it: every 1.4.0 cl ### Added - Switchback experiments, served as the Collector and the Java SDK serve them (the R33 cluster-defined contract). An experiment with `randomizationType: "switchback"` lists in `switchbackClusters`, in order, the unit types it is linked to and the attribute path holding each one's cluster value (`/` nests, a quoted segment is a literal key, an integer segment indexes an array). The first linked unit, in declared order, whose attribute gives a value serves the experiment and its exposure; the value is the cluster key, used raw (never hashed): a non-empty String as is, an Integer as its decimal text, while a Float (`3.0` included), boolean, Hash, Array, `""` or `nil` gives none. The variant is the platform's balanced-block draw for the period `floor((now - switchbackStartAt) / switchbackPeriodMs)` and the experiment's 64-bit seed. No value, disagreeing units or a value outside `switchbackClusterValues` give control and no exposure. That allow-list matches String entries as is and Integer (and boolean) entries by their decimal text (`17` admits `"17"`); switchbacks do not support floats, so a Float entry (`2.5`, `3.0`) never matches any cluster key; so do the time before `switchbackStartAt` and an unservable schedule (a start that is not hour aligned, a period of 0 or less, fewer than two arms), where rules, a strict audience and full-on still apply. Overrides, assignment rules (a split rule over the serving unit), strict audiences, full-on, traffic (on the serving unit) and custom assignments apply in the Collector's order; holdouts never apply to a switchback. One exposure is sent per experiment and period while its assignment is unchanged (a custom assignment, override or refresh that rebuilds it within the period, or a clock that returns to a period no longer among the two most recent, sends one more), stamped with the time that chose the period, and the cluster value is read once per period. Changing a unit's cluster attribute mid-period, before its exposure, is not supported: callers set it before the first read, and a change takes effect in the next period. A period keeps a copy of the cluster-source attribute values it read (a String, Array or Hash, to the depth a path reads), so changing a value passed to `set_attribute` in place does not change the cluster it served or the attributes its own exposure request carries; other attributes are not copied, and an in-place change to a key of an identity-compared Hash is not supported. The Collector resolves the serving unit and cluster again from the published units and attributes at `exposedAt`, so a switchback exposure that the batch would credit to another unit or cluster (an attribute changed within the period, a unit set afterwards, a write in the exposure's millisecond, a clock that stepped back) is published in a request of its own, with the units and attributes its period read and its own `exposedAt`; `publish` then sends more than one request. A string cluster value keys by its published UTF-8 text. The new experiment fields (`randomization_type`, `switchback_clusters`, `switchback_cluster_values`, `switchback_start_at`, `switchback_period_ms`, `switchback_carryover_duration_ms`, `switchback_burn_in_duration_ms`, `switchback_burn_out_duration_ms`, `switchback_design_type`, `switchback_estimand`) are optional; payloads without switchbacks assign, expose and publish as in 1.4.0 (one request per `publish`) and read no extra clock to do so. -- A `contains` operator for audience filters and assignment rule conditions, an alias of `in`, so the app can start sending `contains`: the same `[haystack, needle]` operands and the same result in every case (list membership, substring of a string, key of an object, `null` otherwise). `in` is unchanged. +- A `contains` operator for audience filters and assignment rule conditions, an alias of `in`, so the app can start sending `contains`: the same `[haystack, needle]` operands and the same result in every case (list membership, substring of a string, key of an object, `null` otherwise), as the Elixir, C++, Rust and Scala SDKs have it. `in` is unchanged. Ruby 1.4.0 and earlier (and the JavaScript and Java SDKs at the time of writing) evaluate `contains` to `null`, so a strict audience using it serves control there: send it only once every SDK in use understands it. - `application_version` on `ClientConfig` (also `ClientConfig.new(application_version:)`, the `application_version` property in `create_from_properties`), on `Absmartly.configure_client`, and as an `ABSmartly.new` keyword option; `Client#application_version` returns the value sent. See Fixed. ### Changed @@ -16,7 +16,7 @@ Adds switchback experiments on top of 1.4.0, without breaking it: every 1.4.0 cl - `X-Application-Version` is no longer always `0`: 1.4.0 hardcoded it, with no way to configure it. The configured `application_version` (see Added) is sent when it is a whole number of 1 to 18 digits (an Integer, an integral Float, or a String with surrounding spaces trimmed), and `0` otherwise (`nil`, `"2.4.1"`, a negative number), as the Java and JavaScript SDKs send it; the collector rejects any other value. Who is affected: nobody, unless they configure a version; applications that set one now get it recorded with their events. It is not an audience or rule attribute and is not added to the published attributes. - Every timestamp the SDK sends (`publishedAt`, `exposedAt`, `setAt`, `achievedAt`) is the current time in epoch milliseconds, as the Collector reads it and the JavaScript and Java SDKs send it. Up to 1.4.0 they were the context's creation time in seconds, so every event looked more than 50 years old and stayed at one instant for the context's life. Contexts made by `ABSmartly#create_context`, `create_context_async` and `create_context_with` read a millisecond clock on every call; a `Time` passed to `Context.create` is still one fixed instant, now in milliseconds, and a callable clock (`-> { millis }`) is read on each call. `publishedAt` is never earlier than an event in its batch, so a wall clock that steps back does not get the batch rejected. Who is affected: every published event changes its timestamps (not its content); collectors, proxies and tests that read or compared those values in seconds see milliseconds. - Float unit UIDs are hashed from the text JavaScript's `toFixed(0)` gives (`1.5` as `"2"`, `125.75` as `"126"`, `-0.0` as `"0"`, `-0.4` as `"-0"`, `1e21` as `"1e+21"`), as the JavaScript and Java SDKs and the Collector hash them; 1.4.0 hashed `Float#to_s` (`"1.5"`). Integer (exact decimal text, beyond 2**53 too), BigDecimal and Rational UIDs and UTF-8 strings hash as in 1.4.0. Who is affected: units set with a Float UID; they are reassigned once (they may get another variant) and exposed again, and from then on match every other SDK. -- Unit UIDs in another encoding than UTF-8 (e.g. UTF-16) are transcoded to UTF-8 before hashing, a surrogate pair written as CESU-8 bytes is joined, and a lone surrogate or invalid byte becomes U+FFFD, as the JavaScript SDK's `TextEncoder` encodes them; 1.4.0 hashed the string's own bytes. A binary (`ASCII-8BIT`) string that holds UTF-8 text is hashed as that text; one that is not text (raw bytes such as a `BINARY(16)` id or a digest) keeps 1.4.0's raw-byte hash, so ids that differ in a byte never share a bucket. Who is affected: units set with a non-UTF-8 String UID, or a UTF-8 String holding CESU-8 surrogates or invalid bytes; they are reassigned once and exposed again, and from then on match every other SDK. `get_unit` still returns the UID as set. +- Unit UIDs in another encoding than UTF-8 (e.g. UTF-16) are transcoded to UTF-8 before hashing, a surrogate pair written as CESU-8 bytes is joined, and a lone surrogate or invalid byte becomes U+FFFD, as the JavaScript SDK's `TextEncoder` encodes them; 1.4.0 hashed the string's own bytes. A binary (`ASCII-8BIT`) or US-ASCII string that holds UTF-8 text is hashed as that text; one that is not text (raw bytes such as a `BINARY(16)` id or a digest) keeps 1.4.0's raw-byte hash, so ids that differ in a byte never share a bucket. Who is affected: units set with a non-UTF-8 String UID, or a UTF-8 String holding CESU-8 surrogates or invalid bytes; they are reassigned once and exposed again, and from then on match every other SDK. `get_unit` still returns the UID as set. ## [1.4.0] - 2026-11-17 diff --git a/lib/hashing.rb b/lib/hashing.rb index 7086d680..a9fcacc2 100644 --- a/lib/hashing.rb +++ b/lib/hashing.rb @@ -49,15 +49,15 @@ def self.base64_url_no_padding(bytes) # BMP become the standard 4-byte sequence and each lone surrogate becomes # U+FFFD, matching the JavaScript SDK's TextEncoder-based encoding. Strings in # another encoding (e.g. UTF-16) are transcoded; binary strings are read as - # UTF-8 bytes. A binary string that is not UTF-8 text even after joining - # CESU-8 pairs (raw bytes such as a BINARY(16) id or a digest) is hashed - # from its own bytes, as in 1.4.0: replacing each invalid byte with U+FFFD - # would give distinct byte ids one hash. + # UTF-8 bytes. A binary or US-ASCII string that is not UTF-8 text even after + # joining CESU-8 pairs (raw bytes such as a BINARY(16) id or a digest) is + # hashed from its own bytes, as in 1.4.0: replacing each invalid byte with + # U+FFFD would give distinct byte ids one hash. def self.to_utf8(value) str = value.to_s if str.encoding == Encoding::UTF_8 || str.encoding == Encoding::BINARY || str.encoding == Encoding::US_ASCII return str if str.encoding == Encoding::UTF_8 && str.valid_encoding? - return str.b if str.encoding == Encoding::BINARY && !utf8_text?(str) + return str.b if str.encoding != Encoding::UTF_8 && !utf8_text?(str) bytes = str.b bytes = bytes.gsub(ENCODED_SURROGATE_PAIR) do diff --git a/lib/json_expr/json_expr.rb b/lib/json_expr/json_expr.rb index 5c7a7a89..306e8c56 100644 --- a/lib/json_expr/json_expr.rb +++ b/lib/json_expr/json_expr.rb @@ -33,8 +33,8 @@ def initialize "null": NilOperator.new, "not": NotOperator.new, "in": in_operator, - # The same operator under the name the other SDKs and the app use: - # [haystack, needle], identical to "in" in every case. + # The same operator under the name the Elixir, C++, Rust and Scala SDKs + # use: [haystack, needle], identical to "in" in every case. "contains": in_operator, "match": MatchOperator.new, "eq": EqualsOperator.new, diff --git a/spec/parity_spec.rb b/spec/parity_spec.rb index 44b2ca95..ac58c978 100644 --- a/spec/parity_spec.rb +++ b/spec/parity_spec.rb @@ -78,6 +78,11 @@ y.setbyte(5, (y.getbyte(5) + 1) % 256) expect(Hashing.hash_unit(x)).not_to eq(Hashing.hash_unit(y)), x.unpack1("H*") end + # The same for raw bytes tagged US-ASCII. + x = "\xFF\xFE\x01".dup.force_encoding("US-ASCII") + y = "\xFE\xFF\x01".dup.force_encoding("US-ASCII") + expect(Hashing.hash_unit(x)).to eq(Hashing.base64_url_no_padding(Digest::MD5.digest(x.b))) + expect(Hashing.hash_unit(x)).not_to eq(Hashing.hash_unit(y)) # A lone surrogate written as bytes is still text, as JavaScript encodes it. expect(Hashing.hash_unit("ab\xED\xA0\xBDcd".b)).to eq(lone_surrogate_hash) end From 479fcd56fe5e2acfda7df4f53044201bb65b129a Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 1 Dec 2026 11:59:29 +0000 Subject: [PATCH 11/15] docs: README install hint ~> 1.5 Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c42f314c..61d0d7c3 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ The ABsmartly Ruby SDK is compatible with Ruby versions 2.7 and later. For the b Install the gem and add to the application's Gemfile by executing: ```bash -bundle add absmartly-sdk --version "~> 1.4" +bundle add absmartly-sdk --version "~> 1.5" ``` If bundler is not being used to manage dependencies, install the gem by executing: From 76ca0d194fc27eb3b3078b2375678e1a0c0d2cb4 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 1 Dec 2026 12:28:21 +0000 Subject: [PATCH 12/15] fix: keep Hashing.to_utf8 as in 1.4.0; decide raw-byte ids in hash_unit Review (479fcd5) P3: to_utf8 is public and returned raw bytes for binary or US-ASCII input that is not UTF-8 text. The raw-byte rule now lives in hash_unit, so to_utf8 is byte-identical to 1.4.0 and hashes are unchanged. Regression pins to_utf8's 1.4.0 output. Co-Authored-By: Claude Opus 5.5 --- lib/hashing.rb | 17 ++++++++++------- spec/parity_spec.rb | 3 +++ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/lib/hashing.rb b/lib/hashing.rb index a9fcacc2..c89b708c 100644 --- a/lib/hashing.rb +++ b/lib/hashing.rb @@ -18,8 +18,15 @@ class Hashing def self.hash_unit(value) unit = value.is_a?(Float) ? number_to_fixed0(value) : value.to_s # ASCII text has the same bytes in UTF-8 and every ASCII-compatible - # encoding, so only other text is transcoded. - unit = to_utf8(unit) unless unit.ascii_only? + # encoding, so only other text is transcoded. A binary or US-ASCII string + # that is not UTF-8 text even after joining CESU-8 pairs (raw bytes such + # as a BINARY(16) id or a digest) is hashed from its own bytes, as in + # 1.4.0: replacing each invalid byte with U+FFFD would give distinct byte + # ids one hash. + unless unit.ascii_only? || + ((unit.encoding == Encoding::BINARY || unit.encoding == Encoding::US_ASCII) && !utf8_text?(unit)) + unit = to_utf8(unit) + end base64_url_no_padding(Digest::MD5.digest(unit.b)) end @@ -49,15 +56,11 @@ def self.base64_url_no_padding(bytes) # BMP become the standard 4-byte sequence and each lone surrogate becomes # U+FFFD, matching the JavaScript SDK's TextEncoder-based encoding. Strings in # another encoding (e.g. UTF-16) are transcoded; binary strings are read as - # UTF-8 bytes. A binary or US-ASCII string that is not UTF-8 text even after - # joining CESU-8 pairs (raw bytes such as a BINARY(16) id or a digest) is - # hashed from its own bytes, as in 1.4.0: replacing each invalid byte with - # U+FFFD would give distinct byte ids one hash. + # UTF-8 bytes. def self.to_utf8(value) str = value.to_s if str.encoding == Encoding::UTF_8 || str.encoding == Encoding::BINARY || str.encoding == Encoding::US_ASCII return str if str.encoding == Encoding::UTF_8 && str.valid_encoding? - return str.b if str.encoding != Encoding::UTF_8 && !utf8_text?(str) bytes = str.b bytes = bytes.gsub(ENCODED_SURROGATE_PAIR) do diff --git a/spec/parity_spec.rb b/spec/parity_spec.rb index ac58c978..0e25d53c 100644 --- a/spec/parity_spec.rb +++ b/spec/parity_spec.rb @@ -83,6 +83,9 @@ y = "\xFE\xFF\x01".dup.force_encoding("US-ASCII") expect(Hashing.hash_unit(x)).to eq(Hashing.base64_url_no_padding(Digest::MD5.digest(x.b))) expect(Hashing.hash_unit(x)).not_to eq(Hashing.hash_unit(y)) + # to_utf8 itself still returns UTF-8 text, as in 1.4.0. + expect(Hashing.to_utf8(a).bytes).to eq([239, 191, 189, 239, 191, 189, 1]) + expect(Hashing.to_utf8(x).encoding).to eq(Encoding::UTF_8) # A lone surrogate written as bytes is still text, as JavaScript encodes it. expect(Hashing.hash_unit("ab\xED\xA0\xBDcd".b)).to eq(lone_surrogate_hash) end From 002eb882c3a7279297b92fcb6efef82c7834d143 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 1 Dec 2026 13:13:17 +0000 Subject: [PATCH 13/15] fix: address the CodeRabbit review of #48 Each claim reproduced with a failing regression first (spec/context_switchback_review_spec.rb, client_application_version_spec): - treatment and variable reads take the clock only once a lookup finds a switchback, so an ordinary read next to a switchback keeps 1.4.0's claim-first path and a clock that reads the context is not re-entered; the switchback is still resolved and exposed at that one reading, even when another thread cached the period first. - a direct queue_exposure of a peeked slot is stamped at its own reading. - close (drop_rejected) drops only a rejected switchback request's events and still sends the requests after it; publish and finalize still stop and keep the rest queued. - the batch body carries copies of the cluster-source values it was checked against, so an in-place change before dispatch can't change it. - partial cleanup uses each request's queued events captured before the publisher sees (and may change) the request. - a switchback's identity compares allow-lists by the text each entry admits, so [17] -> [17.0] is an epoch change. - application_version: a non-ASCII-compatible or invalid String falls back to "0" instead of raising. Co-Authored-By: Claude Opus 5.5 --- lib/client.rb | 4 +- lib/context.rb | 149 ++++++++++++++------ spec/client_application_version_spec.rb | 3 +- spec/context_switchback_review_spec.rb | 174 ++++++++++++++++++++++++ spec/context_switchback_spec.rb | 10 +- 5 files changed, 292 insertions(+), 48 deletions(-) create mode 100644 spec/context_switchback_review_spec.rb diff --git a/lib/client.rb b/lib/client.rb index 8259184b..6e491ff0 100644 --- a/lib/client.rb +++ b/lib/client.rb @@ -28,7 +28,9 @@ def self.application_version_header(version) # JavaScript's String(number): the shortest round-trip digits, so 2**56 # is "72057594037927940" as the JavaScript SDK sends it. when Float then version.to_s.to_r.to_i.to_s if version.finite? && version == version.floor - when String then version.strip + # Only ASCII-compatible, valid text can hold the digits; anything else + # (UTF-16, invalid bytes) falls back to "0" rather than raising. + when String then version.strip if version.encoding.ascii_compatible? && version.valid_encoding? end !text.nil? && APPLICATION_VERSION.match?(text) ? text : "0" end diff --git a/lib/context.rb b/lib/context.rb index 2f5e4f2f..f0be0dec 100644 --- a/lib/context.rb +++ b/lib/context.rb @@ -50,9 +50,12 @@ class EventsQueuedWhileClosing < StandardError; end # (nil on the legacy path), their root attribute names, the cache # generation and the schedule identity. SwitchbackEntry = Struct.new(:source_types, :source_paths, :source_roots, :generation, :grid) + # Returned by a variable walk that reached a switchback without a clock + # reading: the walk starts again with one. + NEEDS_CLOCK = Object.new.freeze private_constant :SWITCHBACK, :SWITCHBACK_KEY_SEPARATOR, :SWITCHBACK_RETAINED_PERIODS, :SWITCHBACK_ANCHOR_ALIGNMENT_MS, :SWITCHBACK_MAX_ANCHOR_MS, :SwitchbackEpoch, :SwitchbackState, - :SwitchbackEntry, :SwitchbackSnapshot + :SwitchbackEntry, :SwitchbackSnapshot, :NEEDS_CLOCK attr_reader :pending_count @@ -278,10 +281,17 @@ def set_attributes(attributes) def treatment(experiment_name) check_ready?(true) - # A switchback is resolved, and exposed, at one clock reading. - now = @switchbacks ? now_millis : nil + now = nil while true # rubocop:disable Style/InfiniteLoop -- no block allocation on the read path - assignment = assignment(experiment_name, now) + assignment = assignment(experiment_name, now, true) + # A switchback is resolved, and exposed, at this call's one clock + # reading, taken only once the lookup found a switchback: an ordinary + # experiment keeps 1.4.0's claim-first path, so a clock that reads it is + # not re-entered. + if assignment.nil? + now = now_millis + next + end # set_unit may evict it between the lookup and the exposure claim: # then it is resolved again, so the variant served is the one exposed. return assignment.variant unless claim_and_queue_exposure(assignment, experiment_name, now) == :evicted @@ -524,9 +534,9 @@ def claim_and_queue_exposure(assignment, experiment_name = nil, now = nil) # Only this assignment is claimed, without holding a lock over the # supplied clock; distinct nested or concurrent exposures can proceed. - # A switchback looked up without a reading (see assignment) exposes - # at the reading its slot was resolved at. - exposed_at = assignment.switchback ? now || assignment.serving_read_at : now_millis + # An SDK read exposes a switchback at the reading that chose its + # period; a direct queue_exposure call (no reading) at its own. + exposed_at = assignment.switchback && !now.nil? ? now : now_millis exposure = nil holdout_exposures = nil @queue_mutex.synchronize do @@ -699,7 +709,8 @@ def flush(sealing: false, drop_rejected: false) raise end else - event, response = publish_with_switchbacks(exposures, achievements, switchback_exposures, sent) + event, response = publish_with_switchbacks(exposures, achievements, switchback_exposures, sent, + drop_rejected) end if event.nil? @@ -773,14 +784,12 @@ def remove_published((exposures, exposure_count, achievements, achievement_count end end - # Removes the events of the delivered requests of a partly delivered - # switchback publish; the rest stay queued for the next attempt. - def remove_delivered((exposures, _, achievements, _), events) + # Removes the events of the delivered (or, for close, dropped) requests + # of a partly done switchback publish, given as each request's queued + # events; the rest stay queued for the next attempt. + def remove_delivered((exposures, _, achievements, _), members) sent = Set.new.compare_by_identity - events.each do |event| - event.exposures&.each { |e| sent << e } - event.goals&.each { |g| sent << g } - end + members.each { |events| sent.merge(events) } @queue_mutex.synchronize do @exposures.reject! { |e| sent.include?(e) } if @exposures.equal?(exposures) @achievements.reject! { |g| sent.include?(g) } if @achievements.equal?(achievements) @@ -835,45 +844,88 @@ def publish_event(published_at, units, attributes, exposures, achievements) # unit or cluster (a later set_unit, an attribute set in its millisecond, a # clock rewind) is sent in a request of its own, with the units and # attributes its period read. Requests go in order and stop at the first - # failure. Returns [event, response]: the single request's event, or nil - # once more than one request was delivered (each logged as delivered); - # on a failure, the failed request's event and response. - def publish_with_switchbacks(exposures, achievements, switchback_exposures, sent) + # failure (close, with drop_rejected, drops the rejected request's events + # and sends the rest). Returns [event, response]: the single request's + # event, or nil once more than one request was attempted (each logged); + # on a failure that stops the call, the failed request's event and + # response. + def publish_with_switchbacks(exposures, achievements, switchback_exposures, sent, drop_rejected = false) published_at = now_millis response = nil # The batch body is the snapshot the exposures are checked against, so a - # set_unit or set_attribute racing this publish can't change it. + # set_unit or set_attribute racing this publish can't change it; the + # cluster-source values are copied, so the request carries the values + # that were checked even if the caller changes them in place. units = @units.dup - attributes = @attributes.dup + attributes = batch_attributes(switchback_exposures) separate = separate_switchback_exposures(exposures, switchback_exposures, units, attributes) batch_exposures = separate.nil? ? exposures : exposures.reject { |exposure| separate.key?(exposure) } events = [] + # Each request's queued events, captured before the publisher sees (and + # may change) the request. + members = [] unless batch_exposures.empty? && achievements.empty? events << publish_event(published_at, units, attributes, batch_exposures, achievements) + members << batch_exposures + achievements + end + separate&.each do |exposure, (served_units, served)| + events << publish_event(published_at, served_units, served, [exposure], []) + members << [exposure] end - separate&.each { |exposure, (served_units, served)| events << publish_event(published_at, served_units, served, [exposure], []) } - delivered = [] - events.each do |event| + done = [] + events.each_with_index do |event, i| begin response = @event_handler.publish(self, event) rescue StandardError => e log_error(e) - remove_delivered(sent, delivered) unless delivered.empty? + remove_delivered(sent, done) unless done.empty? raise end - if publish_failed?(response) - remove_delivered(sent, delivered) unless delivered.empty? - return [event, response] - end return [event, response] if events.length == 1 - log_event(ContextEventLogger::EVENT_TYPE::PUBLISH, event) - delivered << event + if publish_failed?(response) + unless drop_rejected + remove_delivered(sent, done) unless done.empty? + return [event, response] + end + + log_publish_failure(response) + else + log_event(ContextEventLogger::EVENT_TYPE::PUBLISH, event) + end + done << members[i] end [nil, response] end + # The attributes for a batch holding switchback exposures, with the value + # of each of their cluster sources copied. + def batch_attributes(switchback_exposures) + roots = nil + switchback_exposures.each_value do |assignment| + source_roots = assignment.switchback_entry.switchback.source_roots + (roots ||= Set.new).merge(source_roots) unless source_roots.nil? + end + return @attributes.dup if roots.nil? + + @attributes.map do |attribute| + next attribute unless roots.include?(attribute.name.to_s.strip) + + Attribute.new(attribute.name, copy_attribute_value(attribute.value), attribute.set_at) + end + end + + def log_publish_failure(response) + if response.is_a?(Exception) + log_error(response) + elsif response.respond_to?(:exception) && response.exception + log_error(response.exception) + else + log_error(StandardError.new("Publish failed (status=#{response.respond_to?(:status) ? response.status : 'unknown'})")) + end + end + # exposure => [units, attributes] for each switchback exposure that the # batch body would credit to another unit or cluster, or nil. def separate_switchback_exposures(exposures, switchback_exposures, units, attributes) @@ -1276,12 +1328,14 @@ def resolve_rule(entry, attrs, unit_pinned_missing, unit_type = entry.data.unit_ # which would reset their exposed flag and expose them again. # now is the caller's clock reading, so a switchback's period, its cluster # attributes and its exposure's exposedAt all agree; without one, the - # clock is read, outside the lock, once a switchback is found (a refresh - # installed the first switchback while the caller read no clock); the - # slot keeps that reading, which its exposure is stamped with. - def assignment(experiment_name, now = nil) - @assignment_mutex.synchronize { cached_or_new_assignment(experiment_name, @state, now) } || - assignment(experiment_name, now_millis) + # clock is read, outside the lock, once a switchback is found; with + # defer_clock nil is returned instead, so the caller takes the reading it + # also exposes with. + def assignment(experiment_name, now = nil, defer_clock = false) + found = @assignment_mutex.synchronize { cached_or_new_assignment(experiment_name, @state, now) } + return found if !found.nil? || defer_clock + + assignment(experiment_name, now_millis) end # nil for a switchback when now is nil. @@ -1456,16 +1510,22 @@ def cached_or_new_assignment(experiment_name, state, now = nil) def resolve_variable_value(key, default_value, expose) key = key.to_s.to_sym winner = nil + now = nil attempts = 0 while true # rubocop:disable Style/InfiniteLoop -- no block allocation on the read path return default_value if attempts >= VARIABLE_WALK_ATTEMPTS attempts += 1 state = @state - # Read once per walk, so every switchback it resolves shares a reading - # (a refresh that installs the first switchback restarts the walk). - now = @switchbacks ? now_millis : nil + # Read once a candidate is a switchback, so every switchback the walk + # resolves shares a reading and an ordinary walk reads no clock + # before its claim; the walk then starts again with that reading. winner = variable_assignment(key, expose, state, now) + if winner.equal?(NEEDS_CLOCK) + attempts -= 1 + now = now_millis + next + end visited = nil winner, visited = winner if winner.is_a?(Array) # A refresh, even one from a holdout's logger, restarts the walk. @@ -1503,7 +1563,8 @@ def variable_assignment(key, expose, state = @state, now = nil) while i < candidates.length # Resolved from the state current under the assignment lock, so a read # that a refresh overtook can't reinstall an old assignment. - assignment = assignment(candidates[i].data.name, now) + assignment = assignment(candidates[i].data.name, now, true) + return NEEDS_CLOCK if assignment.nil? # As in java-sdk, visited candidates' holdouts precede the winner's exposure. if expose && !assignment.holdout_assignments.nil? && (!assignment.exposed || assignment.overridden) && holdouts_pending?(assignment) @@ -1849,7 +1910,11 @@ def switchback_entry(experiment) end def switchback_grid(experiment) - [Experiment.ordered_clusters(experiment.switchback_clusters), experiment.switchback_cluster_values, + values = experiment.switchback_cluster_values + # By the text each entry admits, so [17] and [17.0] (which admits + # nothing) differ although Ruby's == finds them equal. + values = values.map { |value| Absmartly::Switchback::Serving.allowed_text(value) } if values.is_a?(Array) + [Experiment.ordered_clusters(experiment.switchback_clusters), values, experiment.switchback_start_at, experiment.switchback_period_ms, experiment.switchback_design_type] end diff --git a/spec/client_application_version_spec.rb b/spec/client_application_version_spec.rb index 1531bbae..a8607a36 100644 --- a/spec/client_application_version_spec.rb +++ b/spec/client_application_version_spec.rb @@ -38,7 +38,8 @@ def header(version) it "sends 0 for anything else" do ["2.4.1", "1.0", "", " ", "-1", -1, "+1", "1e3", "12a", "1_000", "١", "1\n2", "1000000000000000000", 1_000_000_000_000_000_000, 1.5, -2.0, Float::NAN, Float::INFINITY, - :"123", ["1"], { v: 1 }, true].each do |version| + :"123", ["1"], { v: 1 }, true, "12".encode("UTF-16LE"), "12a".encode("UTF-16LE"), + "1\xFF".dup.force_encoding("UTF-8")].each do |version| expect(header(version)).to eq("0"), version.inspect end end diff --git a/spec/context_switchback_review_spec.rb b/spec/context_switchback_review_spec.rb new file mode 100644 index 00000000..7ed52a2c --- /dev/null +++ b/spec/context_switchback_review_spec.rb @@ -0,0 +1,174 @@ +# frozen_string_literal: true + +require "switchback_support" + +# Regressions for the CodeRabbit review of ruby-sdk#48 (head 76ca0d1). +module ContextSwitchbackReviewSpec + RSpec.describe "Context switchbacks (review regressions)" do + include SwitchbackSpecSupport + + UNIT_TYPE = "store_id" + UID = "e791e240fcd3df7d238cfc285f475e8152fcc0ec" + HOUR = SwitchbackSpecSupport::HOUR + ANCHOR = SwitchbackSpecSupport::ANCHOR + SEED_HI = -5 + SEED_LO = -7 + + let(:clock) { SwitchbackSpecSupport::MutableClock.new(ANCHOR) } + let(:provider) { double("ContextDataProvider") } + + def switchback(id = 1, name = "exp_sb", path = "city", **extra) + { + id: id, name: name, unitType: UNIT_TYPE, iteration: 1, seedHi: SEED_HI, seedLo: SEED_LO, + split: [0.5, 0.5], variants: [{ name: "A", config: nil }, { name: "B", config: nil }], + trafficSeedHi: 1, trafficSeedLo: 2, trafficSplit: [0.0, 1.0], fullOnVariant: 0, + applications: [{ name: "website" }], audienceStrict: false, audience: nil, + randomizationType: "switchback", switchbackClusters: { UNIT_TYPE => path }, + switchbackStartAt: ANCHOR, switchbackPeriodMs: HOUR + }.merge(extra) + end + + def unit_experiment(id, name) + switchback(id, name).merge(randomizationType: nil, switchbackClusters: nil, switchbackStartAt: nil, + switchbackPeriodMs: nil) + end + + def create_context(experiments, attributes: { "city" => "Lisboa" }, publisher: SwitchbackSpecSupport::Publisher.new) + build_context(data_of(experiments), units: { UNIT_TYPE => UID }, attributes: attributes, provider: provider, + publisher: publisher) + end + + def refresh_to(context, experiments) + allow(provider).to receive(:context_data).and_return(ready(data_of(experiments))) + context.refresh + end + + # An exposure the batch would credit to another cluster goes in a request of its own, after the + # goal's request. + def split_publish_context(publisher) + context = create_context([switchback], attributes: {}, publisher: publisher) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + context.treatment("exp_sb") + context.set_attribute("city", "Faro") + context.track("goal") + context + end + + # A clock that reads the context it stamps must not recurse when the payload has a switchback. + it "lets a clock read an ordinary experiment's treatment next to a switchback" do + context = nil + depth = 0 + reentrant = Object.new + reentrant.define_singleton_method(:call) do + depth += 1 + raise "clock re-entered #{depth} times" if depth > 5 + + begin + context.treatment("exp_unit") unless context.nil? + ANCHOR + 10 + ensure + depth -= 1 + end + end + config = ContextConfig.create + config.set_units(UNIT_TYPE => UID) + context = Context.create(reentrant, config, ready(data_of([switchback, unit_experiment(2, "exp_unit")])), nil, + SwitchbackSpecSupport::Publisher.new, nil, DefaultVariableParser.new, + AudienceMatcher.new(DefaultAudienceDeserializer.new)) + expect { context.treatment("exp_unit") }.not_to raise_error + expect(context.pending_count).to eq(1) + end + + # A direct queue_exposure call stamps its own reading, not the peek's. + it "stamps a direct queue_exposure of a peeked slot with the call's own reading" do + context = create_context([switchback]) + clock.now = ANCHOR + 9 + context.peek_treatment("exp_sb") + peeked = context.send(:switchback_resolution_for_test, "exp_sb") + clock.now = ANCHOR + 20 + context.queue_exposure(peeked) + expect(published_exposures(context).map(&:exposed_at)).to eq([ANCHOR + 20]) + end + + # close drops only the rejected request's events; the separate switchback request it never + # attempted is still sent before the context seals. + it "keeps an unattempted switchback request when close's goal request is rejected" do + attempts = [] + publisher = Object.new + publisher.define_singleton_method(:publish) do |_context, event| + attempts << event + next OpenStruct.new(success?: false, status: 503) if event.goals&.any? + + OpenStruct.new(success?: true) + end + context = split_publish_context(publisher) + context.close + expect(attempts.map { |e| [e.goals&.length.to_i, e.exposures&.length.to_i] }).to eq([[1, 0], [0, 1]]) + expect(context.closed?).to be(true) + end + + # The request carries the cluster value its check saw, even if the caller changes the set + # String in place before dispatch. + it "publishes the cluster value the batch check saw" do + captured = [] + publisher = Object.new + city = +"Lisboa" + publisher.define_singleton_method(:publish) do |_context, event| + captured << event.attributes&.map { |a| [a.name, a.value.dup] } + OpenStruct.new(success?: true) + end + context = create_context([switchback], attributes: {}, publisher: publisher) + clock.now = ANCHOR + 10 + context.set_attribute("city", city) + context.treatment("exp_sb") + checked = false + allow(context).to receive(:separate_switchback_exposures).and_wrap_original do |original, *args| + result = original.call(*args) + city.replace("Faro") unless checked + checked = true + result + end + context.publish + expect(captured.flatten(1)).to include(["city", "Lisboa"]) + expect(captured.flatten(1)).not_to include(["city", "Faro"]) + end + + # A publisher that clears a delivered request's goals must not make them queue again. + it "removes delivered goals even when the publisher clears the request" do + attempts = 0 + publisher = Object.new + publisher.define_singleton_method(:publish) do |_context, event| + attempts += 1 + if attempts == 1 + event.goals&.clear + event.exposures&.clear + next OpenStruct.new(success?: true) + end + OpenStruct.new(success?: false, status: 503) + end + context = split_publish_context(publisher) + context.publish + expect(context.pending_count).to eq(1) + end + + # [17] and [17.0] differ: a Float entry admits no cluster, so the refresh is an epoch change. + it "drops an eligible slot when an Integer allow-list entry becomes a Float" do + context = create_context([switchback(path: nil, switchbackClusters: { UNIT_TYPE => "store" }, + switchbackClusterValues: [17])], attributes: { "store" => 17 }) + clock.now = ANCHOR + 10 + context.treatment("exp_sb") + expect(context.send(:switchback_resolution_for_test, "exp_sb").eligible).to be(true) + + refresh_to(context, [switchback(path: nil, switchbackClusters: { UNIT_TYPE => "store" }, + switchbackClusterValues: [17])]) + expect(context.send(:switchback_resolution_for_test, "exp_sb").eligible).to be(true) + + refresh_to(context, [switchback(path: nil, switchbackClusters: { UNIT_TYPE => "store" }, + switchbackClusterValues: [17.0])]) + context.treatment("exp_sb") + slot = context.send(:switchback_resolution_for_test, "exp_sb") + expect([slot.eligible, slot.switchback_silent]).to eq([false, true]) + end + end +end diff --git a/spec/context_switchback_spec.rb b/spec/context_switchback_spec.rb index d0bd5f79..df8c995e 100644 --- a/spec/context_switchback_spec.rb +++ b/spec/context_switchback_spec.rb @@ -440,9 +440,9 @@ def serialized_publish(context) clock.now = ANCHOR + HOUR clock.next_read = ANCHOR + HOUR - 1 end - # A variable read's walk starts again on the refreshed data, at a reading of its own; the - # value and the exposure still come from that one reading. - arm, at = api == :variable_value ? [EXPECTED_2_ARMS[1], ANCHOR + HOUR] : [EXPECTED_2_ARMS[0], ANCHOR + HOUR - 1] + # Every read takes its one reading only once it finds the switchback, so the value and the + # exposure come from that reading. + arm, at = [EXPECTED_2_ARMS[0], ANCHOR + HOUR - 1] expect(worker.value).to eq([arm, []]) expect(EXPECTED_2_ARMS[0]).not_to eq(EXPECTED_2_ARMS[1]) expected = api == :peek_treatment ? [] : [sb_exposure(1, "exp_sb", arm, at, true, true)] @@ -894,13 +894,15 @@ def flags(e) expect(published_exposures(context).map(&:exposed_at)).to eq([ANCHOR + 5, ANCHOR + 9]) end + # A unit experiment next to a switchback reads the clock only for its own exposure, as in 1.4.0: + # the one reading is the one it is stamped with. it "keeps stamping unit experiments at enqueue time" do context = create_context([switchback(randomizationType: "unit"), switchback(2, "exp_other")]) clock.now = ANCHOR + HOUR clock.next_read = ANCHOR + HOUR - 1 variant = context.treatment("exp_sb") - expect(published_exposures(context)).to eq([sb_exposure(1, "exp_sb", variant, ANCHOR + HOUR, true, true)]) + expect(published_exposures(context)).to eq([sb_exposure(1, "exp_sb", variant, ANCHOR + HOUR - 1, true, true)]) end # A grid change that lowers the current index below the retained ones must not evict the slot From 879d9e8ed704b28f4f1beb2f5607f54eee6e61a3 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 1 Dec 2026 14:24:18 +0000 Subject: [PATCH 14/15] perf: keep the deferred-clock lookup off the ordinary read path The CodeRabbit fix (002eb88) cost warm reads 3-4% against 76ca0d1: assignment kept a local and two branches on every cached read, and the variable walk checked NEEDS_CLOCK on payloads without switchbacks. assignment is back to its one-expression shape and the walk checks only once a switchback was installed. Measured (median of 8 interleaved runs) vs 76ca0d1: all paths within +-1%; vs 1.4.0: treatment -4.0%, peek_treatment -6.5%, variable_value -2.9%, create -2.5%, cold paths -0.2%/-0.4%. Co-Authored-By: Claude Opus 5.5 --- lib/context.rb | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/lib/context.rb b/lib/context.rb index f0be0dec..2594adae 100644 --- a/lib/context.rb +++ b/lib/context.rb @@ -1328,14 +1328,12 @@ def resolve_rule(entry, attrs, unit_pinned_missing, unit_type = entry.data.unit_ # which would reset their exposed flag and expose them again. # now is the caller's clock reading, so a switchback's period, its cluster # attributes and its exposure's exposedAt all agree; without one, the - # clock is read, outside the lock, once a switchback is found; with - # defer_clock nil is returned instead, so the caller takes the reading it - # also exposes with. + # clock is read, outside the lock, once a switchback is found. + # With defer_clock, nil is returned for a switchback found without a + # reading instead, so the caller takes the reading it also exposes with. def assignment(experiment_name, now = nil, defer_clock = false) - found = @assignment_mutex.synchronize { cached_or_new_assignment(experiment_name, @state, now) } - return found if !found.nil? || defer_clock - - assignment(experiment_name, now_millis) + @assignment_mutex.synchronize { cached_or_new_assignment(experiment_name, @state, now) } || + (defer_clock ? nil : assignment(experiment_name, now_millis)) end # nil for a switchback when now is nil. @@ -1521,7 +1519,7 @@ def resolve_variable_value(key, default_value, expose) # resolves shares a reading and an ordinary walk reads no clock # before its claim; the walk then starts again with that reading. winner = variable_assignment(key, expose, state, now) - if winner.equal?(NEEDS_CLOCK) + if @switchbacks && winner.equal?(NEEDS_CLOCK) attempts -= 1 now = now_millis next @@ -1563,8 +1561,7 @@ def variable_assignment(key, expose, state = @state, now = nil) while i < candidates.length # Resolved from the state current under the assignment lock, so a read # that a refresh overtook can't reinstall an old assignment. - assignment = assignment(candidates[i].data.name, now, true) - return NEEDS_CLOCK if assignment.nil? + assignment = assignment(candidates[i].data.name, now, true) || (return NEEDS_CLOCK) # As in java-sdk, visited candidates' holdouts precede the winner's exposure. if expose && !assignment.holdout_assignments.nil? && (!assignment.exposed || assignment.overridden) && holdouts_pending?(assignment) From 3a10532650457d27526a6adcf919662adf352836 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 1 Dec 2026 15:00:31 +0000 Subject: [PATCH 15/15] test: pin the deferred clock and close's drop of a rejected request Review (879d9e8) findings, each with a test that kills its mutant: - P2 N53: the variable walk reads the clock only once it reaches a switchback (re-entrant clock through variable_value). - P2 N55: a request close dropped stays dropped when a later request raises (pending_count 1, no double-counted goal on retry). - P3 N54: close logs the dropped request's failure. - P3 N52: the clock restart is not counted against the walk's attempts. - P3: CHANGELOG says close drops only the rejected request and sends the rest, while publish and finalize stop. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- spec/context_switchback_review_spec.rb | 73 ++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d338da69..ca4bd86b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ Adds switchback experiments on top of 1.4.0, without breaking it: every 1.4.0 cl ### Changed - Experiments with `randomizationType: "switchback"` are served as switchbacks. 1.4.0 served a switchback that has a `unitType` as an ordinary experiment on that unit (a sticky variant that ignores clusters and periods). Who moves: units in running switchback experiments, which move to their cluster's schedule; their exposures move to the serving unit and to one per period while the assignment is unchanged. -- When `publish` sends a switchback exposure in a request of its own (see Added), the event logger receives one `"publish"` event per request delivered (a failed request logs an `"error"` event instead and stops the call; delivered requests are not sent again), so one `publish` call can log more than one. Payloads without such an exposure still send one request per `publish`, and none when nothing is queued. +- When `publish` sends a switchback exposure in a request of its own (see Added), the event logger receives one `"publish"` event per request delivered (a failed request logs an `"error"` event instead and stops `publish` and `finalize`, while `close` drops only that request and sends the rest; delivered requests are not sent again), so one `publish` call can log more than one. Payloads without such an exposure still send one request per `publish`, and none when nothing is queued. - The `X-Agent` header is now `absmartly-ruby-sdk/1.5.0`. ### Fixed diff --git a/spec/context_switchback_review_spec.rb b/spec/context_switchback_review_spec.rb index 7ed52a2c..282f2e3b 100644 --- a/spec/context_switchback_review_spec.rb +++ b/spec/context_switchback_review_spec.rb @@ -80,6 +80,55 @@ def split_publish_context(publisher) expect(context.pending_count).to eq(1) end + # The variable walk, too, reads the clock only once it reaches a switchback. + it "lets a clock read an ordinary variable next to a switchback" do + context = nil + depth = 0 + reentrant = Object.new + reentrant.define_singleton_method(:call) do + depth += 1 + raise "clock re-entered #{depth} times" if depth > 5 + + begin + context.variable_value("unit.key", -1) unless context.nil? + ANCHOR + 10 + ensure + depth -= 1 + end + end + unit = unit_experiment(2, "exp_unit").merge(variants: [{ name: "A", config: '{"unit.key":0}' }, + { name: "B", config: '{"unit.key":1}' }]) + config = ContextConfig.create + config.set_units(UNIT_TYPE => UID) + context = Context.create(reentrant, config, ready(data_of([switchback, unit])), nil, + SwitchbackSpecSupport::Publisher.new, nil, DefaultVariableParser.new, + AudienceMatcher.new(DefaultAudienceDeserializer.new)) + expect { context.variable_value("unit.key", -1) }.not_to raise_error + expect(context.pending_count).to eq(1) + end + + # Restarting the walk to take its clock reading is not an overtaken walk: two refreshes during + # a switchback variable read still leave it a walk to finish. + it "does not count the clock restart against the walk's attempts" do + variant_config = [{ name: "A", config: '{"sb.key":0}' }, { name: "B", config: '{"sb.key":1}' }] + context = create_context([switchback(variants: variant_config)]) + clock.now = ANCHOR + 10 + expected = context.peek_variable_value("sb.key", -1) + # Each of the first two walks is overtaken by a refresh that lands after it read the state; + # with the clock restart the third walk still runs. + refreshes = 0 + allow(context).to receive(:variable_assignment).and_wrap_original do |original, *args| + result = original.call(*args) + if refreshes < 2 && !result.equal?(Context.const_get(:NEEDS_CLOCK)) + refreshes += 1 + refresh_to(context, [switchback(variants: variant_config)]) + end + result + end + expect(context.variable_value("sb.key", -1)).to eq(expected) + expect(refreshes).to eq(2) + end + # A direct queue_exposure call stamps its own reading, not the peek's. it "stamps a direct queue_exposure of a peeked slot with the call's own reading" do context = create_context([switchback]) @@ -108,6 +157,30 @@ def split_publish_context(publisher) expect(context.closed?).to be(true) end + # The rejected request close dropped stays dropped when a later request raises, so a retry + # never resends (and double counts) it; the drop is logged as an error. + it "keeps close's dropped request dropped when a later request raises" do + errors = [] + logger = Object.new + logger.define_singleton_method(:handle_event) { |type, data| errors << data if type == ContextEventLogger::EVENT_TYPE::ERROR } + publisher = Object.new + publisher.define_singleton_method(:publish) do |_context, event| + next OpenStruct.new(success?: false, status: 503) if event.goals&.any? + + raise "switchback request failed" + end + context = build_context(data_of([switchback]), units: { UNIT_TYPE => UID }, provider: provider, + publisher: publisher, logger: logger) + clock.now = ANCHOR + 10 + context.set_attribute("city", "Lisboa") + context.treatment("exp_sb") + context.set_attribute("city", "Faro") + context.track("goal") + expect { context.close }.to raise_error("switchback request failed") + expect(context.pending_count).to eq(1) + expect(errors).to eq(["Publish failed (status=503)", "switchback request failed"]) + end + # The request carries the cluster value its check saw, even if the caller changes the set # String in place before dispatch. it "publishes the cluster value the batch check saw" do