Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,23 @@
## [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, 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.
- 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
- 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 `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
- `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`) 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

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.
Expand Down
2 changes: 1 addition & 1 deletion Gemfile.lock
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
30 changes: 27 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ 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:

```bash
gem install absmartly-sdk -v 1.4.0
gem install absmartly-sdk -v 1.5.0
```

## Getting Started
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -318,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

Expand All @@ -332,6 +334,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. 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.
- 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.
Expand Down
19 changes: 12 additions & 7 deletions lib/a_b_smartly.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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?
Expand All @@ -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)
Expand All @@ -114,15 +116,15 @@ 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)
end

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)
Expand All @@ -138,7 +140,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)
Expand All @@ -149,10 +151,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.
Expand Down
Loading
Loading