diff --git a/CHANGELOG.md b/CHANGELOG.md index 890bded4..af5a7b9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,53 +1,57 @@ -## [2.0.0] - Unreleased - -Behavior now matches the JavaScript SDK (the reference implementation). Each Breaking entry says who is affected. - -### Breaking -- After `close`, `experiments`, `set_override` and `set_overrides` no longer raise "ABSmartly Context is closed"; the other read methods still raise it, as in v1.3.0. Before the context is ready, `publish` and `refresh` now raise "ABSmartly Context is not yet ready". Affects code that relied on those raising (or not raising). -- `close` and `refresh` return `nil` (or, for `refresh`, the failure) instead of an Array. Affects code that used their return values. -- `close` and `finalize` after a failed final publish raise the publish error and leave the context open with its events queued, so the caller finds out and can retry: a second `close` republishes and seals, and the `"close"` (or `"finalize"`) event is logged only once the context is sealed. A routine collector rejection (e.g. HTTP 5xx) raises a `PublishError`, a `StandardError`, so it is catchable with an ordinary `rescue`. v1.3.0 sealed the context and orphaned the events. Affects code that called `close` without handling a raised publish error. -- A failed `refresh` no longer marks the context failed: it logs the error, returns it and keeps the current data. `refresh` on a failed context is a no-op. -- The `publish` event is logged only once a publish succeeds; a failed publish logs an `error` event instead. Affects event loggers that counted `publish` events. -- `create_context` no longer raises connection errors such as `Faraday::ConnectionFailed`: the context is returned failed (`failed?` is true) and the error goes to the event logger. `rescue Faraday::ConnectionFailed` around `create_context` no longer triggers. -- A context fetch whose body can't be deserialized now fails the context instead of leaving it never ready. -- Shared variable keys: when several experiments define the same variable, `variable_value` and `peek_variable_value` read from the first experiment, in experiment id order, that the unit is assigned to or overridden in, exposing each experiment visited on the way (as the JavaScript SDK does). v1.3.0 always read and exposed the last experiment in the payload. `variable_keys` likewise now maps a shared key to the experiment with the lowest id instead of the last one in the payload. Affects units in more than one experiment sharing a variable key. -- Numeric audience comparisons follow the JavaScript SDK's number coercion. Affects strict-audience users with numeric attributes, which may move to or from control. -- An audience is re-evaluated after `set_attribute`/`set_attributes` (through the `attrs_seq` counter), as in the JavaScript SDK: when newly supplied attributes flip the audience result, the cached assignment is recomputed, so a unit can move and an extra exposure is sent. v1.3.0 kept the assignment made before the attributes were set. Affects code that set attributes after a treatment or variable read. -- An invalid regex in a `match` audience now sets `audienceMismatch`, so strict audiences assign control. `match` no longer caps pattern/text length. -- Float unit UIDs are hashed from JavaScript's `toFixed(0)` text (e.g. `1.5` as `"2"`), so units with Float UIDs are reassigned. Integer, BigDecimal and Rational UIDs hash as in v1.3.0. -- Strings in non-UTF-8 encodings (e.g. UTF-16) are transcoded to UTF-8 before hashing, so those units are reassigned; surrogate pairs written as CESU-8 are joined and lone surrogates or invalid bytes become U+FFFD. UTF-8 strings are unaffected. -- `track` raises `ArgumentError` for properties that are neither a Hash nor respond to `to_h` (e.g. a String or Array). `ActionController::Parameters` (through `to_unsafe_h`, so unpermitted params are accepted as in v1.3.0) and other `to_h` objects are converted. -- `DefaultContextEventHandler` is a deprecated alias of `DefaultContextPublisher`, so its `.name` is `"DefaultContextPublisher"`. `ContextEventHandler` is likewise an alias of `ContextPublisher`. -- `Array.wrap`, `String#underscore` and `String#compare_to` core extensions removed. +## [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. + +### Added +- Assignment rules. An experiment's `assignmentRules` (a JSON string of `{"rules": [...]}`) are evaluated in order, and the first matching rule decides the variant, taking precedence over the audience and `audienceStrict`, traffic eligibility, full-on and custom assignments; only `set_override` beats a rule. An `assign` rule gives a fixed variant; a `split` rule (e.g. `"percentages": "20/30/50"`) hashes the unit with the experiment's own seed over its percentages, which must be non-negative and sum to 100 within 0.01. Rules can be scoped to `environments` (an empty list matches all) and their `conditions` are JSON expressions over the same attributes as audiences, including `application` and `environment`. Rule-assigned exposures carry `ruleOverride: true`, `assigned: false`, `eligible: true`, so the backend excludes them from analysis. A malformed rule is skipped in favour of the next one; an `assign` variant out of range or a split without one percentage per variant stops evaluation and falls back to normal assignment. While the unit is missing, a split rule gives the experiment's no-unit variant (the full-on variant, otherwise 0); once the unit is set, unexposed ones are re-resolved and exposed ones keep their variant. Invalid `assignmentRules` JSON is ignored for that experiment. A custom audience matcher that only implements `evaluate(audience, attributes)` keeps working: it receives the attributes under the keys they were set with, as in 1.3.0 (plus `"application"`/`"environment"`, see Changed), and rules then run on the default rule engine. +- Holdouts, as in the JavaScript SDK. The context payload's `holdouts` list and each experiment's `holdoutIds` are read (`ContextData#holdouts`, `Experiment#holdout_ids` and `Experiment#holdout_type`, all optional). A unit held out by any holdout covering an experiment gets control for it (variant 0, `assigned: false`; for a shared variable key its control value is used only when no assigned, overridden or rule-won experiment defines the key) and no exposure of its own, ahead of the audience, full-on, traffic and custom assignments; `set_override` and a matching assignment rule still win. Each covering holdout queues one ordinary exposure (the holdout's id and name, the experiment's unit type, its arm as the variant) per unit type, the first time a covered experiment is read with `treatment` or `variable_value`; like any exposure it is sent on `publish` or `close`. The arm is hashed with the covered experiment's unit and the holdout's own seeds; arm 0 holds the unit out and, in a three-arm holdout (a three-entry `split`), arm 1 holds out experiments that are not full-on. A covered 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 (as in the JavaScript SDK); a later refresh that changes the experiment or its coverage can rebuild it. An overridden experiment is the exception, as in the Java SDK: the next `variable_value` read after `set_unit` exposes its holdouts, once each (`treatment` does not), and the override still wins. Unexposed assignments are re-resolved once the unit is set. Arms stay pinned while a holdout's iteration is unchanged, so a seed or split edit does not reassign or expose again. Holdouts without an id, with a split that is not a non-empty list of numbers or with non-integer seeds, and `holdoutIds` that name no holdout, are ignored (the JavaScript SDK may still assign or expose such malformed holdouts). Only integer IDs, integral floats and canonical decimal spellings are accepted; noncanonical text IDs are ignored, even when identical on both sides, and accepted text IDs publish as integers (unlike JavaScript on these malformed inputs). Payloads without holdouts assign and publish exactly as before. +- `semver_eq`, `semver_gt`, `semver_gte`, `semver_lt` and `semver_lte` operators for audience filters and rule conditions. A leading `v`/`V` and `+build` metadata are ignored, missing core parts count as `0`, and a release ranks above its pre-releases; an operand that is not a version gives `null`. A numeric operand is converted to text as the JavaScript SDK does (`toFixed(15)`, trailing zeros trimmed), so `1.0000000000000002` compares equal to `"1"`; other operators are unchanged. +- `Context#finalize`, the name the other ABsmartly SDKs use. Unlike `close`, if the final publish fails it raises the failure (a `StandardError`) and leaves the context open with its events queued, so it can be retried; it logs the `"finalize"` event (`EVENT_TYPE::FINALIZE`) once sealed, and `experiments`, `set_override` and `set_overrides` keep working after it. `close` behaves as in 1.3.0. +- `Context#finalized?`, `#finalizing?`, `#ready_error`, `#get_unit`, `#get_units`, `#get_attribute`, `#get_attributes`, `#custom_field_value_type` and `#wait_until_ready(timeout = nil)`. +- `ABSmartly#create_context_async` and `Absmartly.create_context_async`, which return a context at once and fetch its data on a background thread. +- `Context#variable_keys_list`, mapping each variable key to every experiment that defines it, in experiment id order. +- `ABSmartly.new(endpoint, api_key:, application:, environment:, timeout:, retries:, context_event_logger:)` alongside `ABSmartly.new(config)`. +- `retry_statuses` (on `ClientConfig` and `DefaultHttpClientConfig`) to opt in to retrying HTTP statuses, e.g. `[502, 503, 504]`, and `retry_connection_failures` to opt in to retrying a refused connection on the context fetch (GET only). Both are off by default, so retries are as in 1.3.0. +- `Absmartly::ContextPublisher` and `Absmartly::DefaultContextPublisher`, aliases of `ContextEventHandler` and `DefaultContextEventHandler` under the names the other SDKs use. +- `Client#application` and `Client#environment` readers, `Absmartly::ContextDataResult`, `Absmartly::PublishError` (a `StandardError`), `Context.create`'s optional `application:`/`environment:` keywords, `Exposure#rule_override`, `Experiment#assignment_rules`, and an optional `properties` argument to `track`. ### Changed -- The `X-Agent` header is now `absmartly-ruby-sdk/` instead of `absmartly-ruby-sdk`, as the JavaScript SDK sends its versioned agent. Collectors and proxies that match the exact old value need updating. +- The `X-Agent` header is now `absmartly-ruby-sdk/` instead of `absmartly-ruby-sdk`, as the JavaScript SDK sends its versioned agent. The collector stores it in the export `agent` column, so dashboards, collectors and proxies that match the exact old value need updating. - Every exposure in the publish payload now carries `ruleOverride` (`false` unless an assignment rule chose the variant), as the JavaScript SDK sends it. Consumers that compare the exact publish body (snapshots, proxies) see the extra field. -- Audience filters on `application` or `environment` now see the configured names (see Added), so a non-strict audience with such a condition stops flagging `audienceMismatch` on matching units, and a strict one stops serving them control. +- Audience filters and rule conditions now always see `application` and `environment` (the names configured on the client), matching the JavaScript SDK. A user attribute of the same name wins, even when set after the context is created. Empty or unset names are left out rather than matching `""`. Nothing new is published (the collector attaches both server-side) and `app_version` is never injected. Who moves: units in an experiment whose audience has an `application`/`environment` condition. With Audience enforced (`audienceStrict`) they got control (variant 0) because 1.3.0 never supplied those attributes; a matching unit is now randomised normally and gets a new exposure. Non-strict audiences stop flagging `audienceMismatch` for matching units. +- With the built-in `AudienceMatcher`, an attribute set under both a String and a Symbol name (`"age"` and `:age`) is evaluated with the value set last, in audiences and in rule conditions. 1.3.0 read whichever entry the evaluator found under the String key, so an older String value kept shadowing a newer Symbol one. An attribute name that is neither a String nor a Symbol is read by its text (`to_s`) the same way; 1.3.0's evaluator never found it. Custom audience matchers (including `AudienceMatcher` subclasses) still receive both keys as set, as in 1.3.0. Who moves: units whose attribute was set under both spellings with different values, or under such an object name; they are evaluated on the latest value and can change variant, with a new exposure. +- `treatment` and `variable_value` no longer route their exposures through the public `Context#queue_exposure`. Calling `queue_exposure(assignment)` directly on an open context works as in 1.3.0 (same signature, returns the exposure logger's result, `nil` once exposed); queueing a new exposure after `close` raises `IllegalStateException` (see Fixed), while one already exposed still returns `nil`. Who moves: code that subclassed, reopened or `prepend`ed `Context` to override `queue_exposure`. Overriding it no longer intercepts exposures: reads never call it. That was never a supported hook; the supported way to observe exposures is a context event logger, which receives each one as an `"exposure"` (`ContextEventLogger::EVENT_TYPE::EXPOSURE`) event. +- `variable_value` and `peek_variable_value` return the caller's default when the unit is not assigned to the experiment, as the JavaScript SDK does (cross-SDK scenario 48): its unit type is not set on the context, or it fails an enforced (`audienceStrict`) audience, and no override or assignment rule applies. 1.3.0 returned variant 0's (control's) value in both cases. Such a read no longer queues an exposure for the experiment (1.3.0 published one with `assigned: false`); `treatment` still does. Units outside the traffic split or in a full-on experiment read their variant's value as before, and the exposure is still queued. Who moves: code that reads variables for such units and relied on getting control's config instead of its own default, and analyses that counted those `assigned: false` exposures. +- Shared variable keys: when several experiments define the same variable, only one of them, chosen by experiment id, is read and exposed; see Fixed for the rule. 1.3.0 always read and exposed the last experiment in the payload. `variable_keys` keeps its shape (key to one experiment name) but now names the experiment with the lowest id. Who moves: units in more than one experiment that share a variable key. +- `track` raises `ArgumentError` ("Goal '' properties must be of type object.") for properties that are neither a Hash nor respond to `to_h` (e.g. a String or Array). 1.3.0 queued them, and the collector, which reads goal properties as an object, rejected the whole publish, losing every exposure and goal in it. `ActionController::Parameters` (through `to_unsafe_h`, so unpermitted params are accepted as in 1.3.0) and other `to_h` objects are converted. Who moves: code passing non-object properties to `track`. +- `set_unit` with a unit type given as a String now raises "Unit '...' already set." when the type already has a different UID, as the README always said and as it did for a Symbol type; 1.3.0 silently replaced the UID, so later exposures and goals were published under a different unit than the earlier ones. Who moves: code that calls `set_unit("type", uid)` twice with different UIDs on one context (create a new context for the new identity instead). +- `create_context` and `refresh` no longer raise connection errors such as `Faraday::ConnectionFailed` out of the fetch, as an HTTP error response already didn't in 1.3.0. `create_context` returns the context failed (`failed?` is true, reads return control and the caller's defaults); `refresh` keeps the current data. Either way the error goes to the event logger. Who moves: code that wraps `create_context` or `refresh` in `rescue Faraday::ConnectionFailed` (check `context.failed?` or the logged `"error"` event instead). +- The `"publish"` event is logged once a publish is delivered, as its documentation says ("`publish()` method succeeds"); a failed publish logs an `"error"` event instead. 1.3.0 logged `"publish"` before sending and logged nothing when the collector rejected the batch. Who moves: event loggers that counted `"publish"` events for failed publishes. +- `close` and `finalize` bound callback-driven publishing to two passes. If events are still queued after the second successful pass, they remain queued and the context stays open; a catchable retry error is raised instead of silently discarding accepted events or looping forever. A close or finalize requested by a callback in the meantime also stays pending and is carried out by the next successful publish. A `close` or `finalize` requested from inside a publish callback in that state, or from the `"error"` callback of a rejected publish, keeps the events queued and is carried out on the next successful `publish` (if that deferred seal's own publish is rejected, a deferred `finalize` stays pending and raises the rejection out of that `publish`, while a deferred `close` logs it and seals, as `close` does; if the publisher raises, either stays pending and the error is re-raised), without making the current `publish` raise (the `"error"` event for a rejected publish is new in 1.4.0, see the `"publish"` entry above). Who moves: applications that enqueue events from publish callbacks or concurrently while sealing; retry the sealing method after producers stop. +- A failed `publish` keeps its events queued and sends them with the next publish (1.3.0 dropped them), so `pending_count` stays above zero until a publish succeeds. A publisher that raises during `close` leaves the context open with the events queued instead of losing them. Who moves: code that reads `pending_count` after a failed publish, and collectors, which now receive the retried batch. +- A `refresh` that was already in flight when the initial async fetch failed, and then succeeds, recovers the context: it installs the data and clears `failed?` and `ready_error`, and events still queued are published with the next `publish` (exposures made while failed are unassigned, `assigned: false` with experiment id 0, and control unless an override forces a variant; assignments read while failed, overrides included, are resolved again when the recovered data has the experiment, so later reads and exposures carry it; such an assignment already exposed while failed is therefore exposed once more after recovery, with the real experiment id, while one for an experiment the recovered data still lacks is kept and not exposed again; if a later refresh then supplies that experiment, the override's variant is still served, and this release resolves it again: the next read exposes it once with the real id and reads the recovered variant's variables. Keeping the cached assignment without a new exposure, as the Java and JavaScript SDKs do, is also accepted, so do not rely on either); a `publish` made while the context was failed still drops its events, as in 1.3.0. A `refresh` called after the context failed is still a no-op, as in 1.3.0. Who moves: code that relied on a failed async context staying failed after an in-flight refresh completed. +- A failed `refresh` logs the error and keeps the current data (1.3.0 marked the context failed and served control for every experiment from then on); it still returns what the event logger returned. Who moves: units of a long-lived context after a refresh fails, which keep their variants instead of dropping to control. +- Numeric audience comparisons compare numbers, following the JavaScript SDK's number coercion; 1.3.0 compared their text, so `10 > 9` was false. Who moves: units whose numeric attributes the text comparison misjudged; with a strict audience they move between control and their variant. +- An invalid regex in a `match` audience counts as an audience mismatch (strict audiences give control), as in the JavaScript SDK; 1.3.0 ignored the whole audience. Who moves: units in experiments whose audience has an invalid `match` pattern. ### Fixed -- Nested `variants`, `applications` and `customFieldValues` in the context payload are read by key: an unknown key no longer fails the whole context and a reordered object no longer swaps fields (the bug dates back to v1.3.0). A missing key leaves that field `nil`. -- A `customFieldValues` entry with no `type` (or `type: null`) no longer makes `create_context` or `refresh` raise `NoMethodError`; its value is read as plain text and `custom_field_type` returns `nil` (the bug dates back to v1.3.0). -- `set_unit` stores the `to_s` text of any non-numeric UID (Symbols, `Rack::Session::SessionId`, UUID value objects), as in v1.3.0; `nil` or blank text raises "UID must not be blank." -- Integer unit UIDs are hashed from their exact decimal text, as in v1.3.0, so IDs beyond 2**53 keep distinct buckets. -- `Client#context_data` returns a new immutable `ContextDataResult` per call, so concurrent `create_context_async` calls and refreshes sharing a client can't read each other's in-flight state. The client's `data_future`, `exception` and `promise` readers still reflect the latest fetch. -- A raising event logger no longer breaks the operation that logs (initialization, treatment, publish). -- The SDK writes nothing to stderr, as in v1.3.0; failures are reported to the event logger as `error` events. -- `ABSmartly.new(config)` accepts a duck-typed config that responds to `to_hash` on Ruby 2.7. +- A context fetch whose body can't be deserialized fails the context instead of leaving it never ready. +- `ContextDataResult`, `PublishError`, `ContextPublisher`, `DefaultContextPublisher` and the semver comparator and operators live under the `Absmartly` namespace, so none of them can clash with an application's own classes. +- Nested `variants`, `applications` and `customFieldValues` in the context payload are read by key: an unknown key no longer fails the whole context and a reordered object no longer swaps fields. Unknown experiment fields are ignored without writing to stderr. A custom field with a missing or `null` `type` is read as text, and `custom_field_type` returns `nil`, instead of raising `NoMethodError` out of `create_context`/`refresh`. - `in` with an object haystack finds symbol keys (audience attributes are parsed with symbolized names). - An indeterminate audience result (no filter) keeps a cached assignment instead of re-assigning. +- `set_unit` accepts the same UID again when it differs only by surrounding spaces, or comes as a String instead of a number (`123` then `"123"`); 1.3.0 raised "Unit '...' already set." for a Symbol unit type in the first case. Integer and Float UIDs keep their value (`get_unit` returns the number) and hash exactly as in 1.3.0; `set_unit` still returns the UID's text. +- `Client#context_data` returns a new immutable `Absmartly::ContextDataResult` per call (with the same `success?`, `data_future`, `exception` and `promise` readers), so concurrent `create_context_async` calls and refreshes sharing a client can't read each other's in-flight state. The client's own readers still reflect the latest fetch. +- `ContextEventLoggerCallback` no longer calls ActiveSupport's `present?`, so it works outside Rails. +- A raising event logger no longer breaks the operation that logs (initialization, treatment, publish). +- `ABSmartly.new(config)` accepts a duck-typed config that responds to `to_hash` on Ruby 2.7. - An exposure or goal can no longer be queued after `close` sealed the context. +- Clearing the override of an experiment the context data doesn't have returns control again; 1.3.0 kept returning the cleared forced variant. Who moves: units whose override of such an experiment is cleared get control instead of the stale forced variant, with one more control exposure. +- Shared variable keys: the wrong experiment could win a variable key that several experiments define, and experiments that were only checked got exposures. 1.3.0 read and exposed the last experiment in the payload that defined the key, even when the unit was not in it (an enforced audience it failed, or a unit type not set on the context). Users were recorded in experiments they never saw, which biases the results. Now, as in the Java SDK: the experiments whose variants define the key are checked in experiment id order; the first one the unit is assigned to, overridden in or rule-assigned in wins, and only it is exposed. If the winner's variant lacks the key, the caller's default is returned (no later experiment is read). If none wins, a held-out unit reads the first held-out experiment's control value, otherwise the default is returned, with no experiment exposure. The holdouts covering each experiment checked on the way are still exposed, before the winner's own exposure, as in the Java SDK. `peek_variable_value` exposes nothing. A read that a `refresh` overtakes starts again on the new data, so its value and exposures come from one snapshot (except a holdout exposure whose own logger callback refreshes, which is already queued); if refreshes keep landing during the read (a matcher or logger callback that refreshes), it stops after three attempts and returns the default with no experiment exposure. Who moves: anyone with two or more running experiments that define the same variable key. + +## [1.3.0] - 2026-01-26 ### Added -- Assignment rules. An experiment's `assignmentRules` (a JSON string of `{"rules": [...]}`) are evaluated in order, and the first matching rule decides the variant, taking precedence over the audience and `audienceStrict`, traffic eligibility, full-on and custom assignments; only `set_override` beats a rule. An `assign` rule gives a fixed variant; a `split` rule (e.g. `"percentages": "20/30/50"`) hashes the unit with the experiment's own seed over its percentages, which must be non-negative and sum to 100 within 0.01. Rules can be scoped to `environments` (an empty list matches all) and their `conditions` are JSON expressions over the same attributes as audiences, including `application` and `environment`. Rule-assigned exposures carry `ruleOverride: true`, `assigned: false`, `eligible: true`, so the backend excludes them from analysis. A malformed rule is skipped in favour of the next one; an `assign` variant out of range or a split without one percentage per variant stops evaluation and falls back to normal assignment. While the unit is missing, a split rule gives the experiment's no-unit variant (the full-on variant, otherwise 0); once the unit is set, unexposed ones are re-resolved and exposed ones keep their variant. Invalid `assignmentRules` JSON is ignored for that experiment. A custom audience matcher that only implements `evaluate(audience, attributes)` keeps working: rules then run on the default rule engine. -- Holdouts, as in the JavaScript SDK. The context payload's `holdouts` list and each experiment's `holdoutIds` are read (`ContextData#holdouts`, `Experiment#holdout_ids` and `Experiment#holdout_type`, all optional). A unit held out by any holdout covering an experiment gets control for it (variant 0, `assigned: false`; control variable values are a fallback when no assigned, overridden or rule-won experiment supplies the key) and no exposure of its own, ahead of the audience, full-on, traffic and custom assignments; `set_override` and a matching assignment rule still win. Each covering holdout queues one ordinary exposure (the holdout's id and name, the experiment's unit type, its arm as the variant) per unit type, the first time a covered experiment is read with `treatment` or `variable_value`; like any exposure it is sent on `publish` or `close`. The arm is hashed with the covered experiment's unit and the holdout's own seeds; arm 0 holds the unit out and, in a three-arm holdout (a three-entry `split`), arm 1 holds out experiments that are not full-on. A covered 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 (as in the JavaScript SDK); a later refresh that changes the experiment or its coverage can rebuild it. Unexposed assignments are re-resolved once the unit is set. Arms stay pinned while a holdout's iteration is unchanged, so a seed or split edit does not reassign or expose again. Holdouts without an id, with a split that is not a non-empty list of numbers or with non-integer seeds, and `holdoutIds` that name no holdout, are ignored (the JavaScript SDK may still assign or expose such malformed holdouts). Only integer IDs, integral floats and canonical decimal spellings are accepted; noncanonical text IDs are ignored, even when identical on both sides, and accepted text IDs publish as integers (unlike JavaScript on these malformed inputs). Payloads without holdouts assign and publish exactly as before. -- `semver_eq`, `semver_gt`, `semver_gte`, `semver_lt` and `semver_lte` operators for audience filters and rule conditions. A leading `v`/`V` and `+build` metadata are ignored, missing core parts count as `0`, and a release ranks above its pre-releases; an operand that is not a version gives `null`. A numeric operand is converted to text as the JavaScript SDK does (`toFixed(15)`, trailing zeros trimmed), so `1.0000000000000002` compares equal to `"1"`; other operators are unchanged. -- Audience filters now always evaluate `application` and `environment` (the application and environment names configured on the client), matching the JavaScript SDK. The SDK seeds the audience evaluation map with these system values first, then overlays user-set attributes, so a user attribute of the same name always wins, even when set after the context is created (it re-evaluates the cached assignment through `attrs_seq`). Empty or unset names are skipped, so a filter on `environment` with no environment configured leaves the key absent rather than matching `""`. Nothing new is published: the collector already attaches `application` and `environment` server-side, so the publish payload gains no `application`/`environment`/`app_version` attributes. `app_version` is never injected into the evaluation map. **This changes assignment for running experiments: a unit whose experiment has Audience enforced (`audienceStrict`) and an `environment`/`application` condition currently gets variant 0 (control) because the SDK never supplied those attributes; after upgrading, a unit that matches the audience is randomised normally, while a unit that does not match still gets control.** -- `Context#finalize`, which logs the `"finalize"` event (`EVENT_TYPE::FINALIZE`); `close` still logs `"close"` (`EVENT_TYPE::CLOSE`). -- `Context#variable_keys_list`, mapping each variable key to every experiment that defines it, in experiment id order; `variable_keys` still maps it to a single experiment name (see Breaking for which one). -- `retry_statuses` (on `ClientConfig` and `DefaultHttpClientConfig`) to opt in to retrying HTTP statuses, e.g. `[502, 503, 504]`. None are retried by default, as in v1.3.0. -- `retry_connection_failures` to opt in to retrying a refused connection on the context fetch (GET only). Off by default: with the default `max_retries` and backoff, a refused connection would block for about 15 s. -- `ABSmartly.new(endpoint, api_key:, application:, environment:, ...)` alongside `ABSmartly.new(config)`. - Configurable connection pool settings: `pool_size` and `pool_idle_timeout` ## [0.1.0] - 2022-08-03 diff --git a/Gemfile.lock b/Gemfile.lock index c869625b..d82861a7 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - absmartly-sdk (2.0.0) + absmartly-sdk (1.4.0) base64 (~> 0.2) faraday (~> 2.0) faraday-net_http_persistent (~> 2.0) diff --git a/README.md b/README.md index 9fce47b3..37c23b44 100644 --- a/README.md +++ b/README.md @@ -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 +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 +gem install absmartly-sdk -v 1.4.0 ``` ## Getting Started @@ -174,7 +174,9 @@ if context.ready? end ``` -Read methods (`treatment`, `peek_treatment`, `variable_value`, `peek_variable_value`, `variable_keys`, `experiments`, `custom_field_keys`, `custom_field_value`) raise `IllegalStateException` ("ABSmartly Context is not yet ready") until the context is ready, and ("ABSmartly Context is closed") after `close`. Check `ready?` first. A context whose data fetch failed is ready and failed: reads return control (0) and the caller's defaults. +A `refresh` that was already in flight when the initial fetch failed, and then installs data, recovers the context (a failed `refresh` installs nothing, and a `refresh` called after the context failed is a no-op, as in 1.3.0): it installs the data, clears `failed?` and `ready_error`, and events still queued are published with the next `publish`. Exposures made while the context was failed are unassigned (`assigned: false`, experiment id 0; control unless an override forces a variant), which the collector excludes from analysis; a `publish` made while the context was failed still drops its events, as in 1.3.0. A `refresh` that succeeds before the background fetch lands makes the context ready with the refreshed data; that data is kept when the initial fetch completes later, and the `"ready"` event is logged once the initial fetch completes. + +Read methods (`treatment`, `peek_treatment`, `variable_value`, `peek_variable_value`, `variable_keys`, `experiments`, `custom_field_keys`, `custom_field_value`) raise `IllegalStateException` ("ABSmartly Context is not yet ready") until the context is ready, and ("ABSmartly Context is closed") after `close` or `finalize` (except `experiments`, which still works after `finalize`). Check `ready?` first. A context whose data fetch failed is ready and failed: reads return control (0) and the caller's defaults. Or using the global configuration approach: @@ -261,6 +263,10 @@ default_button_color = 'red' button_color = context.variable_value('button.color', default_button_color) ``` +#### Shared variable keys + +When several experiments define the same variable key, the SDK checks the experiments whose variants define it in experiment id order. The first one the unit is assigned to, overridden in or rule-assigned in wins, and only that experiment is exposed. If the winner's variant does not define the key, `variable_value` returns your default rather than reading a later experiment. If no experiment wins, a held-out unit reads the control value of the first held-out experiment; otherwise your default is returned and no experiment is exposed. `peek_variable_value` follows the same rule without exposing anything. + ### Peek at Treatment Variants Although generally not recommended, it is sometimes necessary to peek at a treatment or variable without triggering an exposure. The ABsmartly SDK provides `peek_treatment` and `peek_variable_value` methods for that. @@ -318,13 +324,13 @@ Rule conditions are audience expressions, so they can use your attributes, `appl Experiments can be covered by holdouts set up on the Web Console. A holdout keeps a share of units out of every experiment it covers, so you can measure the combined effect of those experiments. The SDK handles this for you: no code changes are needed. -- A held-out unit gets control (variant 0; control variable values are a fallback when no assigned, overridden or rule-won experiment supplies the key) for each covered experiment, and no exposure is queued for that experiment. +- A held-out unit gets control (variant 0; for a shared variable key its control value is used only when no other experiment defining the key wins, see [Shared variable keys](#shared-variable-keys)) for each covered experiment, and no exposure is queued for that experiment. - The holdout queues its own exposure, once per unit type, the first time the unit sees a covered experiment, whether it is held out or not. Like every exposure, it reaches the collector on `publish` or `close`. - A unit held out by any of the holdouts covering an experiment is held out of it. - A holdout with three arms holds full-on experiments out only in its first arm, and other experiments in its first two arms. - `set_override` and a matching assignment rule still win over a holdout; the holdout's exposure is still queued. - 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. +- 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. ### Custom Assignments @@ -370,13 +376,23 @@ context.publish The `close` method will ensure all events have been published to the ABsmartly collector, like `publish`, and will also "seal" the context, throwing an error if any method that could generate an event is called. -If the final publish fails, `close` raises the failure, the context stays open and the events stay queued, so `close` can be called again to retry. The raised error is a `StandardError`, so it can be caught with an ordinary `rescue`. +If the collector rejects the final publish, `close` logs an `"error"` event, drops that batch and still seals the context, as in v1.3.0. Events tracked while that request was in flight are not part of the rejected batch, so `close` sends them before sealing. ```ruby context.close ``` -`finalize` does the same as `close`, but logs the `"finalize"` event instead of `"close"`. +`finalize` works like the other ABsmartly SDKs: if the final publish fails it raises the failure (a `StandardError`, so an ordinary `rescue` catches it), the context stays open and the events stay queued, so `finalize` can be called again to retry. It logs the `"finalize"` event instead of `"close"`, and `experiments`, `set_override` and `set_overrides` keep working after it. + +```ruby +begin + context.finalize +rescue StandardError => e + # retry later: the events are still queued +end +``` + +Both sealing methods allow one extra publish for events queued during the first request. If events are still queued after that extra publish (whether it succeeded, or `close` dropped its rejected batch), they stay queued, the context stays open, and the method raises `StandardError` ("Events queued while closing; retry close or finalize"); those events are not sent in the same call, so retry after the producer stops. Otherwise a rejection follows the rules above: `close` logs the error, drops that batch and seals (as in v1.3.0), and `finalize` raises the rejection and stays open. ### Custom Event Logger diff --git a/lib/a_b_smartly.rb b/lib/a_b_smartly.rb index 62d31419..d607049c 100644 --- a/lib/a_b_smartly.rb +++ b/lib/a_b_smartly.rb @@ -64,7 +64,7 @@ def initialize_from_config(config) end if @context_event_handler.nil? - @context_event_handler = DefaultContextPublisher.new(@client) + @context_event_handler = DefaultContextEventHandler.new(@client) end end @@ -103,7 +103,7 @@ def initialize_from_params(endpoint, api_key, application, environment, timeout, @client = Client.create(client_config) @context_data_provider = DefaultContextDataProvider.new(@client) - @context_event_handler = DefaultContextPublisher.new(@client) + @context_event_handler = DefaultContextEventHandler.new(@client) @context_event_logger = event_logger @variable_parser = DefaultVariableParser.new @audience_deserializer = DefaultAudienceDeserializer.new @@ -131,7 +131,7 @@ def create_context_async(config) data_future = data_provider.context_data context.set_data(data_future) rescue => e - context.set_data(ContextDataResult.failure(e)) + context.set_data(Absmartly::ContextDataResult.failure(e)) end context end diff --git a/lib/absmartly/version.rb b/lib/absmartly/version.rb index 0156af41..6c6f1315 100644 --- a/lib/absmartly/version.rb +++ b/lib/absmartly/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Absmartly - VERSION = "2.0.0" + VERSION = "1.4.0" end diff --git a/lib/audience_matcher.rb b/lib/audience_matcher.rb index 650acf0b..95eed2e2 100644 --- a/lib/audience_matcher.rb +++ b/lib/audience_matcher.rb @@ -7,8 +7,9 @@ class AudienceMatcher attr_accessor :deserializer, :json_expr SPLIT_PERCENTAGES_SUM_TOLERANCE = 0.01 - # The longest decimal prefix JavaScript's parseFloat accepts. - FLOAT_PREFIX = /\A\s*([+-]?(?:Infinity|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?))/.freeze + # The longest decimal prefix JavaScript's parseFloat accepts, after the + # ECMAScript white space and line terminators (U+FEFF included, U+0085 not). + FLOAT_PREFIX = /\A[\t\n\v\f\r\u2028\u2029\uFEFF\p{Zs}]*([+-]?(?:Infinity|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?))/.freeze RuleAction = Struct.new(:variant, :split) do def split? diff --git a/lib/client.rb b/lib/client.rb index ebf7a236..cd0231ce 100644 --- a/lib/client.rb +++ b/lib/client.rb @@ -72,7 +72,7 @@ def publish(event) # A routine collector rejection must stay catchable with a normal # `rescue StandardError` when close/finalize raises it, so use a # StandardError subclass rather than Ruby's base Exception. - return PublishError.new(response.body) + return Absmartly::PublishError.new(response.body) end response @@ -95,17 +95,17 @@ def fetch_context_data begin promise = @http_client.get(@url, @query, @headers) rescue StandardError => e - return ContextDataResult.failure(e) + return Absmartly::ContextDataResult.failure(e) end unless promise.success? - return ContextDataResult.failure(Exception.new(promise.body), promise) + return Absmartly::ContextDataResult.failure(Exception.new(promise.body), promise) end content = (promise.body || {}).to_s data = @deserializer.deserialize(content, 0, content.size) - return ContextDataResult.failure(StandardError.new("Failed to deserialize context data"), promise) if data.nil? + return Absmartly::ContextDataResult.failure(StandardError.new("Failed to deserialize context data"), promise) if data.nil? - ContextDataResult.new(data, nil, promise) + Absmartly::ContextDataResult.new(data, nil, promise) end end diff --git a/lib/context.rb b/lib/context.rb index bf07ca1b..44a25085 100644 --- a/lib/context.rb +++ b/lib/context.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +# Fiber.current and Fiber#alive? before Ruby 3.1. +require "fiber" require_relative "hashing" require_relative "type_utils" require_relative "variant_assigner" @@ -17,8 +19,15 @@ class Context # readers see either the complete old or the complete new state. State = Struct.new(:data, :index, :index_variables, :custom_fields) NO_RULES = "" + SEAL_FLUSH_PASSES = 2 + private_constant :SEAL_FLUSH_PASSES + class EventsQueuedWhileClosing < StandardError; end + private_constant :EventsQueuedWhileClosing NO_HOLDOUTS = {}.freeze private_constant :NO_HOLDOUTS + # After this many overtaken walks a read returns the default, exposing nothing. + VARIABLE_WALK_ATTEMPTS = 3 + private_constant :VARIABLE_WALK_ATTEMPTS attr_reader :pending_count @@ -47,7 +56,7 @@ def initialize(clock, config, data_future, data_provider, variable_parser, audience_matcher, application, environment) if data_future.success? - assign_data(data_future.data_future) + @state = build_state(data_future.data_future) log_event(ContextEventLogger::EVENT_TYPE::READY, data_future.data_future) else set_data_failed(data_future.exception) @@ -58,27 +67,36 @@ def initialize(clock, config, data_future, data_provider, def set_data(data_future) ready_data = nil failure = nil + # Skip building a payload a refresh has already superseded; ready? is + # rechecked under the lock before a built snapshot is installed. + state = data_future.success? && !ready? ? build_state(data_future.data_future) : nil @ready_mutex.synchronize do - if data_future.success? - assign_data(data_future.data_future) - ready_data = data_future.data_future + # A refresh may already have installed data while the initial fetch was + # in flight: keep it, so a late success doesn't replace newer data and + # a late failure is only logged. + if ready? + failure = data_future.exception unless data_future.success? + elsif state + @state = state else - set_data_failed(data_future.exception) failure = data_future.exception + set_data_failed(failure) end + ready_data = @state.data unless @failed @ready_condvar.broadcast end # User callbacks run outside the readiness lock so they may call # wait_until_ready. - if failure.nil? - log_event(ContextEventLogger::EVENT_TYPE::READY, ready_data) - else - log_error(failure) - end + log_error(failure) unless failure.nil? + log_event(ContextEventLogger::EVENT_TYPE::READY, ready_data) unless ready_data.nil? end def wait_until_ready(timeout = nil) + # Called from a variable parser while this thread builds the data that + # would make the context ready: waiting here could never finish. + return self if building? + @ready_mutex.synchronize do unless ready? || failed? if timeout @@ -113,7 +131,7 @@ def finalized? end def finalizing? - !@closed && @closing + !@closed && @sealing.positive? end attr_reader :ready_error @@ -135,24 +153,25 @@ def get_attribute(name) end def get_attributes - result = {} - @attributes.each do |attr| - result[attr.name] = attr.value - end - result + user_attributes end def experiments check_ready?(false) + check_not_closed_by_close? @state.data.experiments.map(&:name) end def set_override(experiment_name, variant) + check_not_closed_by_close? + @overrides[experiment_name.to_s.to_sym] = variant end def set_overrides(overrides) + check_not_closed_by_close? + @overrides.merge!(overrides.transform_keys(&:to_sym)) end @@ -183,27 +202,30 @@ def custom_assignment(experiment_name) def set_unit(unit_type, uid) check_not_closed? - if uid.nil? - raise IllegalStateException.new("Unit '#{unit_type}' UID must not be blank.") - elsif Absmartly::TypeUtils.numeric?(uid) + if Absmartly::TypeUtils.numeric?(uid) trimmed = uid else # Like v1.3.0, any other value (Symbol, session id, UUID object) is # stored as its to_s text. uid = uid.respond_to?(:to_str) ? uid.to_str : uid.to_s - trimmed = Hashing.to_utf8(uid).strip - if trimmed.empty? - raise IllegalStateException.new("Unit '#{unit_type}' UID must not be blank.") - end + trimmed = uid.strip end previous = @units[unit_type.to_sym] - if !previous.nil? && previous != trimmed + # Compared as text, so 123456 and "123456" are the same unit, as in v1.3.0. + if !previous.nil? && previous.to_s != trimmed.to_s raise IllegalStateException.new("Unit '#{unit_type}' already set.") end - @units[unit_type.to_sym] = trimmed - invalidate_assignments_missing_unit(unit_type.to_s) + if trimmed.is_a?(String) && trimmed.empty? + raise IllegalStateException.new("Unit '#{unit_type}' UID must not be blank.") + end + + if previous.nil? + @units[unit_type.to_sym] = trimmed + invalidate_assignments_missing_unit(unit_type.to_s) + end + trimmed.to_s end def set_units(units) @@ -228,9 +250,12 @@ def set_attributes(attributes) def treatment(experiment_name) check_ready?(true) - assignment = assignment(experiment_name) - queue_exposure(assignment) - assignment.variant + while true # rubocop:disable Style/InfiniteLoop -- no block allocation on the read path + assignment = assignment(experiment_name) + # 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 + end end # A held-out experiment publishes no exposure of its own, unless an override @@ -238,30 +263,9 @@ def treatment(experiment_name) # 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). def queue_exposure(assignment) - exposure = nil - holdout_exposures = nil - @queue_mutex.synchronize do - # Checked under the queue lock so an exposure cannot slip in after close - # sealed the queue and be stranded. - check_not_closed? - - unless assignment.exposed - assignment.exposed = true - - if !assignment.suppressed || assignment.overridden || assignment.rule_override - exposure = enqueue_exposure(assignment.name, assignment) - end - assignment.holdout_assignments&.each_with_index do |holdout_assignment, i| - next if holdout_assignment.nil? || holdout_assignment.exposed - - holdout_assignment.exposed = true - (holdout_exposures ||= []) << enqueue_exposure(assignment.holdouts[i].name, holdout_assignment) - end - end - end - # User callbacks run outside the lock so they can call publish/track. - log_event(ContextEventLogger::EVENT_TYPE::EXPOSURE, exposure) unless exposure.nil? - holdout_exposures&.each { |e| log_event(ContextEventLogger::EVENT_TYPE::EXPOSURE, e) } + result = nil + claim_and_queue_exposure(assignment) { |logged| result = logged } + result end def peek_treatment(experiment_name) @@ -272,8 +276,9 @@ def peek_treatment(experiment_name) alias peek peek_treatment - # Maps each variable key to the name of the experiment whose value - # variable_value returns for it, as in v1.3.0. + # Maps each variable key to one experiment name, as in v1.3.0: the + # lowest-id experiment defining it, which is not necessarily the one whose + # value variable_value returns (see variable_keys_list). def variable_keys check_ready?(true) @@ -365,34 +370,48 @@ def track(goal_name, properties = nil) end def publish - check_ready?(true) + check_not_closed? flush end def refresh - check_ready?(true) + check_not_closed? return nil if @failed data_future = @data_provider.context_data if data_future.success? - assign_data(data_future.data_future) + state = build_state(data_future.data_future) + # Committed under the readiness lock, so a waiter on a context created + # asynchronously wakes, and an initial fetch that failed while this + # refresh was in flight no longer leaves the context failed. + Thread.handle_interrupt(Object => :never) do + @ready_mutex.synchronize do + @state = state + @failed = false + @data_failed = nil + @ready_error = nil + @ready_condvar.broadcast + end + end log_event(ContextEventLogger::EVENT_TYPE::REFRESH, data_future.data_future) - nil else log_error(data_future.exception) - data_future.exception end end - # Publishes pending events, then seals the context. If the final publish - # fails the context stays open with the events queued and the failure is - # raised, so close can be retried. Logs the "close" event only once the - # context is sealed; finalize does the same but logs "finalize". + # Publishes pending events, then seals the context and logs "close", as in + # v1.3.0: a publish the collector rejects is logged as an error and the + # context is still sealed. A publisher that raises propagates the error and + # leaves the context open with the events queued. def close seal(ContextEventLogger::EVENT_TYPE::CLOSE) end + # Like close, but as the JavaScript SDK does: if the final publish fails, the + # failure is raised and the context stays open with the events queued, so + # finalize can be retried. Logs "finalize" once sealed, and set_override, + # set_overrides and experiments keep working afterwards. def finalize seal(ContextEventLogger::EVENT_TYPE::FINALIZE) end @@ -408,49 +427,182 @@ def inspect end private + # SDK reads check the cache under the assignment lock; a direct + # queue_exposure call has nothing to check and may already hold it (from a + # custom matcher), so it skips it. + def with_assignment_lock_if(locked, &block) + locked ? @assignment_mutex.synchronize(&block) : yield + end + + # Claims and queues assignment's exposure. With experiment_name, the claim + # is taken only while the assignment is still the cached one for that + # experiment (checked under the assignment lock, which set_unit also + # 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) + return if assignment.exposed + + claimed = false + begin + loop do + status = nil + # Waiting for the assignment lock stays interruptible; only the claim + # bookkeeping under it is masked. + with_assignment_lock_if(experiment_name) do + Thread.handle_interrupt(Object => :never) do + @queue_mutex.synchronize do + check_not_closed? + owner = @exposing[assignment] + status = + if owner + # Another thread's exposure is in flight; this thread's own + # (a reentrant read from its clock) uses the outer one. + owner.equal?(Thread.current) ? :reentered : :waiting + elsif assignment.exposed + :exposed + # On the SDK's read paths (experiment_name given), a no-unit + # split assignment whose unit has since been set is stale too + # (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)) + @exposing[assignment] = Thread.current + claimed = true + :claimed + else + :evicted + end + end + end + end + return :evicted if status == :evicted + break unless status == :waiting + + @queue_mutex.synchronize do + owner = @exposing[assignment] + @exposure_condvar.wait(@queue_mutex) if owner && !owner.equal?(Thread.current) + end + end + return unless claimed + + # 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 + exposure = nil + holdout_exposures = nil + @queue_mutex.synchronize do + # Checked under the queue lock so an exposure cannot slip in after close + # sealed the queue and be stranded. + check_not_closed? + + unless assignment.exposed + assignment.exposed = true + + # A held-out experiment publishes no exposure of its own, unless an + # 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 + exposure = enqueue_exposure(assignment.name, assignment, exposed_at) + end + assignment.holdout_assignments&.each_with_index do |holdout_assignment, i| + next if holdout_assignment.nil? || holdout_assignment.exposed + + holdout_assignment.exposed = true + (holdout_exposures ||= []) << enqueue_exposure(assignment.holdouts[i].name, holdout_assignment, exposed_at) + end + end + end + ensure + # Only the claim is released here (no assignment lock, so an unwinding + # timeout is not held up). A no-unit assignment left unexposed after its + # unit was set is rebuilt by the next read (see cached_or_new_assignment). + if claimed + Thread.handle_interrupt(Object => :never) do + @queue_mutex.synchronize do + @exposing.delete(assignment) + @exposure_condvar.broadcast + end + end + end + end + # User callbacks run outside the lock so they can call publish/track. + logged = log_event(ContextEventLogger::EVENT_TYPE::EXPOSURE, exposure) unless exposure.nil? + holdout_exposures&.each { |e| log_event(ContextEventLogger::EVENT_TYPE::EXPOSURE, e) } + yield logged if block_given? && !exposure.nil? + nil + end + def seal(event_type) return nil if @closed # Called from a logger callback while a publish is in flight: defer so the - # events queued by the callback are still sent before finalizing. + # events queued by the callback are still sent before finalizing. A seal + # that is already running does not claim it, so the request survives if + # that seal fails or gives up. if @publish_mutex.owned? - @close_pending = event_type + @deferred_mutex.synchronize do + @close_pending = event_type + @close_requests += 1 + end return nil end - @closing = true + close = event_type == ContextEventLogger::EVENT_TYPE::CLOSE + registered = false begin - loop do - result = flush - raise_publish_failure(result) if !@failed && publish_failed?(result) + Thread.handle_interrupt(Object => :never) do + @queue_mutex.synchronize { @sealing += 1 } + registered = true + end + # One extra pass sends events a logger callback queued during the + # first publish; after that raise with the remaining events queued, + # so a callback can't keep close publishing forever or lose events. + SEAL_FLUSH_PASSES.times do |pass| + # close drops a batch the collector rejected, as in v1.3.0, but only + # that batch; anything queued meanwhile is still sent or kept. + result = flush(sealing: true, drop_rejected: close) + last_pass = pass == SEAL_FLUSH_PASSES - 1 + raise_publish_failure(result) if !close && publish_failed?(result) sealed = @queue_mutex.synchronize do next :done if @closed - next :retry unless @exposures.empty? && @achievements.empty? - @closed = true + unless @exposures.empty? && @achievements.empty? + raise EventsQueuedWhileClosing.new("Events queued while closing; retry close or finalize") if last_pass + + next :retry + end + + Thread.handle_interrupt(Object => :never) do + @sealed_by = event_type + @closed = true + end :sealed end return nil if sealed == :done next if sealed == :retry - log_event(event_type, nil) - return nil + logged = log_event(event_type, nil) + return close ? logged : nil end + nil ensure - @closing = false + if registered + Thread.handle_interrupt(Object => :never) do + @queue_mutex.synchronize { @sealing -= 1 } + end + end end end - def flush - if @failed - @queue_mutex.synchronize do - @exposures = [] - @achievements = [] - @pending_count = 0 - end - return @data_failed - end + # sealing: this flush is a seal's own pass, so it neither starts another + # seal nor claims a deferred one. Any other publish (on any thread) may. + def flush(sealing: false, drop_rejected: false) + dropped, failure = @failed ? @ready_mutex.synchronize { drop_if_failed(sealing) } : [false, nil] + return failure if dropped # Serialize publishes so a queued event is part of at most one in-flight # request; on failure the events stay queued for the next attempt. @@ -458,63 +610,146 @@ def flush # deadlock or re-send the in-flight snapshot; the outer call owns it. return nil if @publish_mutex.owned? - result = @publish_mutex.synchronize do - exposures = achievements = nil - event_count = 0 - @queue_mutex.synchronize do - exposures = @exposures.dup - achievements = @achievements.dup - event_count = exposures.size + achievements.size - end + claimed = nil + begin + result = @publish_mutex.synchronize do + exposures = achievements = nil + sent = nil + event_count = 0 + # Failure installation and recovery both take this lock. Keep the + # decision and snapshot together, but never hold it across publishing. + dropped, failure = @ready_mutex.synchronize do + failed_result = drop_if_failed(sealing) + unless failed_result.first + @queue_mutex.synchronize do + exposures = @exposures.dup + achievements = @achievements.dup + event_count = exposures.size + achievements.size + # Which arrays were sent and how much of each: the queues only + # 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] + end + end + failed_result + end + next failure if dropped - next nil unless event_count > 0 + if event_count.zero? + # Assigned under the mask, so an interrupt can't land between + # clearing the request and recording that this publish holds it. + Thread.handle_interrupt(Object => :never) { claimed = take_close_pending } unless sealing + 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 - 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 + end - if response.is_a?(Exception) - log_error(response) - response - elsif response.respond_to?(:exception) && response.exception - log_error(response.exception) - response - elsif response.respond_to?(:success?) && !response.success? - log_error(StandardError.new("Publish failed (status=#{response.respond_to?(:status) ? response.status : 'unknown'})")) - response - else - log_event(ContextEventLogger::EVENT_TYPE::PUBLISH, event) - # Remove only the events that were published; others may have been - # queued concurrently while the request was in flight. - @queue_mutex.synchronize do - @exposures.shift(exposures.size) - @achievements.shift(achievements.size) - @pending_count = [@pending_count - event_count, 0].max + if publish_failed?(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 + remove_published(sent) if drop_rejected + response + else + log_event(ContextEventLogger::EVENT_TYPE::PUBLISH, event) + remove_published(sent) + # Claim a deferred close while still holding the lock, so only this + # successful publish can carry it out; a request made by another + # thread after a rejected publish waits for its own success. + # Assigned under the mask, so an interrupt can't land between + # clearing the request and recording that this publish holds it. + Thread.handle_interrupt(Object => :never) { claimed = take_close_pending } unless sealing + response end - response end + + if claimed + claimed = nil if run_deferred_seal(claimed) + end + result + ensure + # A deferred seal claimed by this publish that did not finish stays + # pending for the next successful publish: one not started (an + # interrupt landed after the claim), one that left events queued, or + # one whose own publish was rejected, raised or was interrupted (a + # Timeout or Thread#kill). Any error still propagates. + restore_close_pending(claimed) if claimed end + end + + # A failed context drops its queued events. Called under the readiness + # lock, which a recovering refresh also holds while it clears @failed, so + # goals tracked after recovery are never dropped by a publish that saw the + # context failed. publish gets the load error, as in v1.3.0; a seal's own + # pass gets nil, since dropping them is not a publish failure. + def drop_if_failed(sealing) + return [false, nil] unless @failed + + @queue_mutex.synchronize do + @exposures = [] + @achievements = [] + @pending_count = 0 + end + [true, sealing ? nil : @data_failed] + end + + # Removes the sent prefix of each queue, unless a failed-context publish + # replaced that queue while the request was in flight (then the batch is + # already gone and the new queue holds only newer events). + def remove_published((exposures, exposure_count, achievements, achievement_count)) + @queue_mutex.synchronize do + @exposures.shift(exposure_count) if @exposures.equal?(exposures) + @achievements.shift(achievement_count) if @achievements.equal?(achievements) + @pending_count = @exposures.size + @achievements.size + end + end + + def take_close_pending + @deferred_mutex.synchronize do + next nil unless @close_pending - if @close_pending - event_type = @close_pending + claimed = [@close_pending, @close_requests] @close_pending = false - seal(event_type) unless @closed || publish_failed?(result) + claimed + end + end + + # True once the seal finished; false when events were still queued. + def run_deferred_seal(claimed) + seal(claimed.first) + true + rescue EventsQueuedWhileClosing + false + end + + # Unless the context sealed or a newer request was made meanwhile (even + # one another publish has already claimed). + def restore_close_pending((event_type, request)) + Thread.handle_interrupt(Object => :never) do + @deferred_mutex.synchronize do + @close_pending = event_type unless @closed || @close_requests != request + end end - result end def publish_failed?(result) @@ -524,23 +759,27 @@ def publish_failed?(result) end def raise_publish_failure(result) - if result.is_a?(Exception) + if result.is_a?(StandardError) raise result + elsif result.is_a?(Exception) + raise StandardError.new(result.message), cause: result elsif result.respond_to?(:exception) && result.exception - raise result.exception + raise_publish_failure(result.exception) else status = result.respond_to?(:status) ? result.status : "unknown" raise StandardError.new("Publish failed (status=#{status})") end end - def enqueue_exposure(name, assignment) + # Called under the queue lock; exposed_at is read before taking it, since a + # supplied clock may call back into the context. + def enqueue_exposure(name, assignment, exposed_at) exposure = Exposure.new exposure.id = assignment.id || 0 exposure.name = name exposure.unit = assignment.unit_type exposure.variant = assignment.variant - exposure.exposed_at = @clock.to_i + exposure.exposed_at = exposed_at exposure.assigned = assignment.assigned exposure.eligible = assignment.eligible exposure.overridden = assignment.overridden @@ -560,6 +799,11 @@ def check_not_closed? end end + # After finalize these still work, as in the JavaScript SDK. + def check_not_closed_by_close? + check_not_closed? if @sealed_by == ContextEventLogger::EVENT_TYPE::CLOSE + end + def check_ready?(expect_not_closed) if !ready? raise IllegalStateException.new("ABSmartly Context is not yet ready") @@ -586,24 +830,94 @@ def experiment_matches(experiment, assignment) # when set after the context was created (the @attrs_seq bump re-evaluates # the cached assignment). Empty system values were skipped at init, so a # missing config leaves the key out rather than matching on "". + # The latest value per name, keyed as the caller set it. Private so an + # override of the public get_attributes doesn't change matcher inputs. + def user_attributes + result = {} + @attributes.each { |attr| result[attr.name] = attr.value } + result + end + def attributes_map - attrs = @system_attributes.dup + # User attributes keep the caller's key, as v1.3.0 passed them to custom + # matchers. A system entry is added only when no user attribute has that + # name as a String or Symbol, the forms audience conditions can read. + user = user_attributes + attrs = {} + @system_attributes.each do |name, value| + attrs[name] = value unless user.key?(name) || user.key?(name.to_sym) + end + attrs.merge!(user) + end + + # The built-in evaluator reads a name as a String or a Symbol, so it gets + # one entry per name: the latest value set under either spelling. + def evaluator_attributes + attrs = {} + @system_attributes.each { |name, value| attrs[name] = value } @attributes.each { |attr| attrs[attr.name.to_s] = attr.value } attrs end + # Custom matchers get the caller's keys (as in v1.3.0); the built-in one + # gets the latest value per name. + def matcher_attributes(matcher) + matcher.instance_of?(AudienceMatcher) ? evaluator_attributes : attributes_map + end + + # A built-in audience matcher is also the rule matcher, and the evaluator + # never changes its input, so the map built for the rules is reused. + def audience_attributes(rule_attrs) + return rule_attrs if !rule_attrs.nil? && @audience_matcher.instance_of?(AudienceMatcher) + + matcher_attributes(@audience_matcher) + end + # A split rule or a holdout resolved while its unit was missing gave the - # no-unit result; once the unit is set, unexposed ones are rebuilt. Exposed - # ones stay, so the user never switches variant or gets a second exposure. + # no-unit result; once the unit is set, unexposed ones are rebuilt. Exposed ones + # stay, so the user never switches variant or gets a second exposure. + # One being exposed right now (its clock is running) is kept: it is + # about to be queued with its variant, so evicting it would serve one + # variant and expose two. If that exposure fails, the next read or claim + # finds it stale and resolves it again. def invalidate_assignments_missing_unit(unit_type) @assignment_mutex.synchronize do + exposing = @queue_mutex.synchronize { @exposing.dup } @assignment_cache.delete_if do |_name, assignment| - assignment.unit_type.to_s == unit_type && !assignment.exposed && - (assignment.rule_missing_unit || assignment.holdout_assignments&.include?(nil)) + assignment.unit_type.to_s == unit_type && !assignment.exposed && missing_unit?(assignment) && + !exposing.key?(assignment) end end end + # A no-unit split assignment whose unit has since been set, that is not + # exposed and not being exposed: set_unit skipped evicting it because its + # exposure was in progress, and that exposure did not complete. + def stale_missing_unit?(assignment) + return false unless unit_now_set?(assignment) + + !exposed_or_exposing?(assignment) + end + + # Read together under the queue lock: an exposure completing sets exposed + # and releases its claim under that lock, so a reader can't see neither. + def exposed_or_exposing?(assignment) + # exposed only moves false -> true: the positive result is stable. + return true if assignment.exposed + + @queue_mutex.synchronize { assignment.exposed || @exposing.key?(assignment) } + end + + # Resolved while its unit was missing: a no-unit split rule, or a holdout + # whose arm could not be computed yet. + def missing_unit?(assignment) + assignment.rule_missing_unit || (!assignment.holdout_assignments.nil? && assignment.holdout_assignments.include?(nil)) + end + + def unit_now_set?(assignment) + missing_unit?(assignment) && !assignment.unit_type.nil? && !@units[assignment.unit_type.to_sym].nil? + end + # Arm 0 always holds the unit out. In a 3-arm holdout arm 1 is "full-on # only", so it holds out experiments that are not full-on. The arm count # comes from the split, never from holdoutType. @@ -671,11 +985,13 @@ def audience_matches(entry, assignment) return false if key_changed && key.empty? && assignment.rule_override if @attrs_seq > (assignment.attrs_seq || 0) || key_changed - attrs = attributes_map - + rule_attrs = nil unless key.empty? - pinned_missing = assignment.exposed && assignment.rule_missing_unit - rule = resolve_rule(entry, attrs, pinned_missing) + # Exposed, or being exposed right now (its clock may set the unit): + # 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) return false if rule&.first != assignment.rule_variant assignment.rule_missing_unit = rule ? rule.last : false @@ -685,7 +1001,7 @@ def audience_matches(entry, assignment) # evaluated here either; only a rule can take it out of suppression. if !assignment.rule_override && !assignment.suppressed && !experiment.audience.nil? && experiment.audience.size > 0 - match = @audience_matcher.evaluate(experiment.audience, attrs) + match = @audience_matcher.evaluate(experiment.audience, audience_attributes(rule_attrs)) # An indeterminate result (no filter, bad JSON) keeps the cached flag. new_audience_mismatch = match.nil? ? assignment.audience_mismatch : !match.result @@ -747,6 +1063,23 @@ def cached_or_new_assignment(experiment_name, state) override = @overrides[exp_key] experiment = experiment(experiment_name.to_s, state) + # Built from the empty snapshot of a failed context that a refresh has + # since recovered with the experiment: resolved again against the + # recovered data. The marker stays on the old assignment, so a rebuild + # that raises leaves it ineligible for reuse. + # (The failed snapshot has no experiments, so a read on it never matches.) + if @failed_marked && !assignment.nil? && !experiment.nil? && + assignment.instance_variable_get(:@failed_snapshot) + assignment = nil + end + # Inline guard: only an unexposed no-unit result can be stale, and the + # check itself takes the queue lock. + if !assignment.nil? && !assignment.exposed && + (assignment.rule_missing_unit || assignment.holdout_assignments&.include?(nil)) && + stale_missing_unit?(assignment) + assignment = nil + end + if !assignment.nil? if !override.nil? if assignment.overridden && assignment.variant == override && @@ -756,7 +1089,7 @@ def cached_or_new_assignment(experiment_name, state) elsif experiment.nil? # A rule-won assignment came from the experiment's rules, so it is # rebuilt once the experiment is gone. - return assignment if !assignment.assigned && !assignment.rule_override + return assignment if !assignment.assigned && !assignment.rule_override && !assignment.overridden elsif (custom.nil? || assignment.rule_override || assignment.suppressed || (custom == assignment.variant && (assignment.custom || assignment.exposed))) && experiment_matches(experiment.data, assignment) && @@ -803,7 +1136,8 @@ def cached_or_new_assignment(experiment_name, state) assignment.traffic_split = data.traffic_split assignment.full_on_variant = data.full_on_variant assignment.rule_key = experiment.rule_key - rule = assignment.rule_key.empty? ? nil : resolve_rule(experiment, attributes_map, false) + rule_attrs = assignment.rule_key.empty? ? nil : matcher_attributes(rule_matcher) + rule = rule_attrs.nil? ? nil : resolve_rule(experiment, rule_attrs, false) assignment.rule_variant = rule&.first assignment.rule_missing_unit = rule ? rule.last : false @@ -816,7 +1150,7 @@ def cached_or_new_assignment(experiment_name, state) assignment.variant = 0 else if !data.audience.nil? && data.audience.size > 0 - match = @audience_matcher.evaluate(data.audience, attributes_map) + match = @audience_matcher.evaluate(data.audience, audience_attributes(rule_attrs)) assignment.audience_mismatch = true if match && !match.result end @@ -853,36 +1187,164 @@ def cached_or_new_assignment(experiment_name, state) assignment.variables = experiment.variables[assignment.variant] || {} end + failed_built = state.equal?(@failed_state) + # A read that finishes after a refresh recovered the context must not + # replace what was resolved against the recovered data, unless that + # data lacks the experiment too and would resolve it the same way. + if failed_built && !@state.equal?(@failed_state) && !experiment(experiment_name.to_s).nil? + return assignment + end + + # Provenance belongs to the new assignment before the single cache + # write. An interrupted replacement leaves the old assignment marked; + # a marker on an uncached replacement has no effect on later reads. + if failed_built + assignment.instance_variable_set(:@failed_snapshot, true) + @failed_marked = true + end @assignment_cache[experiment_name.to_s] = assignment assignment end - # Like the JavaScript SDK, a key shared by several experiments reads from - # the first one, in experiment id order, that the unit is assigned to or - # overridden in; each experiment visited on the way is exposed. When none - # wins, a held-out unit reads the control value of the first held-out - # experiment rather than the default. + # As java-sdk Context.getVariableAssignment resolves a key shared by + # several experiments: the first one, in experiment id order, that the + # unit is assigned to, overridden in or rule-assigned in wins, and only + # that one is exposed. A winner whose variant lacks the key gives the + # default; the walk never moves past it. When none wins, a held-out unit + # reads the first held-out experiment (control, or the default if its + # control lacks the key). A non-peek read still exposes the holdouts of + # each candidate it visits, as java-sdk does. def resolve_variable_value(key, default_value, expose) - state = @state key = key.to_s.to_sym + winner = 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) + visited = nil + winner, visited = winner if winner.is_a?(Array) + # A refresh, even one from a holdout's logger, restarts the walk. + next unless @state.equal?(state) + + unless visited.nil? + i = 0 + while i < visited.length && @state.equal?(state) + queue_holdout_exposures(visited[i]) + i += 1 + end + next unless @state.equal?(state) + end + 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 + end + return default_value if winner.nil? || winner.variables.nil? || !winner.variables.key?(key) + + winner.variables[key] + end + + # 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) + candidates = state.index_variables[key] + return nil if candidates.nil? + + visited = nil suppressed_fallback = nil - (state.index_variables[key] || []).each do |experiment| - assignment = assignment(experiment.data.name) - next if assignment.variables.nil? + i = 0 + # An index loop, not each: no block frame per candidate on the read path. + 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) + # 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) + (visited ||= []) << assignment + end + if assignment.assigned || assignment.overridden || assignment.rule_override + return visited ? [assignment, visited] : assignment + end + + suppressed_fallback ||= assignment if assignment.suppressed + i += 1 + end + visited ? [suppressed_fallback, visited] : suppressed_fallback + end - queue_exposure(assignment) if expose - if assignment.variables.key?(key) && (assignment.assigned || assignment.overridden || assignment.rule_override) - return assignment.variables[key] + # Whether a candidate has a holdout arm still to expose (or, for an + # override, one still to resolve). A warm read past an exposed loser then + # collects nothing. + def holdouts_pending?(assignment) + arms = assignment.holdout_assignments + i = 0 + while i < arms.length + arm = arms[i] + if arm.nil? + unit_type = assignment.unit_type + return true if assignment.overridden && !unit_type.nil? && !@units[unit_type.to_sym].nil? + elsif !arm.exposed + return true end - if assignment.suppressed && !assignment.overridden && !assignment.rule_override - suppressed_fallback ||= assignment.variables + i += 1 + end + false + end + + # Replaces the arms of an override still missing them, once its unit is + # set; the holdout arm cache is written under the assignment lock. + def resolve_late_holdout_arms(assignment) + arms = assignment.holdout_assignments + return unless unit_now_set?(assignment) && arms.include?(nil) + + @assignment_mutex.synchronize do + arms = assignment.holdout_assignments + # The live holdouts (a refresh's equivalent list, if any): the arms are + # decided now, so they and their exposures' names come from those, as + # java-sdk resolves an override's holdouts against the installed data. + holdouts = assignment.matched_holdouts || assignment.holdouts + if arms.include?(nil) + assignment.holdout_assignments = arms.each_with_index.map do |arm, i| + arm || holdout_assignment(holdouts[i], assignment.unit_type) + end + assignment.holdouts = holdouts end end + end + + # Exposes the holdouts covering a visited candidate, from the arms pinned + # in its assignment, without exposing the candidate itself. + def queue_holdout_exposures(assignment) + return if assignment.exposed && !assignment.overridden + + # As java-sdk resolves an override's holdouts live on each visit, an + # arm an override could not get before its unit was set is resolved + # once the unit is, so its holdout is exposed even after the override. + resolve_late_holdout_arms(assignment) if assignment.overridden + holdout_assignments = assignment.holdout_assignments + return if holdout_assignments.nil? - return suppressed_fallback[key] if !suppressed_fallback.nil? && suppressed_fallback.key?(key) + # 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 } - default_value + exposed_at = @clock.to_i + holdout_exposures = nil + @queue_mutex.synchronize do + check_not_closed? + holdout_assignments.each_with_index do |holdout_assignment, i| + next if holdout_assignment.nil? || holdout_assignment.exposed + + holdout_assignment.exposed = true + (holdout_exposures ||= []) << enqueue_exposure(assignment.holdouts[i].name, holdout_assignment, exposed_at) + end + end + holdout_exposures&.each { |e| log_event(ContextEventLogger::EVENT_TYPE::EXPOSURE, e) } end def experiment(experiment, state = @state) @@ -897,7 +1359,86 @@ def variant_assigner(unit_type, unit_hash) @assigners[unit_type] ||= VariantAssigner.new(unit_hash) end - def assign_data(data) + # Builds the snapshot for data, calling the variable parser; callers run + # it outside the readiness lock so a parser may call wait_until_ready. + # The membership bookkeeping defers asynchronous interrupts (Timeout, + # Thread#raise), so one landing while it waits for the lock can't leave + # this thread registered or unbalanced. The parsing keeps the caller's + # interrupt mask: interruptible by default, deferred if the caller masked. + # Ruby can't run the parse under the caller's mask inside a masked + # cleanup, so an interrupt landing as the cleanup starts can skip it; a + # registration only counts while the thread is inside build_state (see + # building?), and the next build or wait drops one left behind. + def build_state(data) + thread = Thread.current + nested = build_state_on_stack?(1) + registered = false + begin + Thread.handle_interrupt(Object => :never) do + @ready_mutex.synchronize do + # [count, fiber that registered first]. A count left by an + # interrupted cleanup in this fiber, with no build of it still + # running further up the stack, is dropped first. + entry = @building_threads[thread] + # (The stack is checked above, before entering these blocks.) + entry = nil if entry && (entry[1].equal?(Fiber.current) ? !nested : !entry[1].alive?) + @building_threads[thread] = entry ? [entry[0] + 1, entry[1]] : [1, Fiber.current] + end + registered = true + end + build_state_maps(data) + ensure + if registered + Thread.handle_interrupt(Object => :never) do + @ready_mutex.synchronize do + entry = @building_threads[thread] + if entry && entry[0] > 1 + @building_threads[thread] = [entry[0] - 1, entry[1]] + elsif entry + @building_threads.delete(thread) + end + end + end + end + end + end + + # True while this thread is building a snapshot (a variable parser calling + # back). A registration whose build has unwound without its cleanup is + # dropped here, so the thread waits like any other. + def building? + thread = Thread.current + entry = @ready_mutex.synchronize { @building_threads[thread] } + return false if entry.nil? + return true unless stale_build_entry?(entry) + + Thread.handle_interrupt(Object => :never) do + @ready_mutex.synchronize { @building_threads.delete(thread) if @building_threads[thread].equal?(entry) } + end + false + end + + # A backtrace covers only the current fiber, so the stack is checked only + # from the fiber that registered; a parser that waits from a nested fiber + # still counts as building. A registering fiber that has ended is stale. + def stale_build_entry?(entry) + fiber = entry[1] + return !build_state_on_stack?(0) if fiber.equal?(Fiber.current) + return true unless fiber.alive? + # Ruby 3.0+ can read the registering fiber's stack from a fiber it + # resumed; 2.7 cannot, so there a live registering fiber still counts. + return false unless fiber.respond_to?(:backtrace_locations) + + !build_state_on_stack?(0, fiber.backtrace_locations || []) + end + + # Whether more than skip build_state frames are on this thread's stack. + # Called only outside build_state's blocks, so each frame is one build. + def build_state_on_stack?(skip, locations = caller_locations) + locations.count { |location| location.path == __FILE__ && location.base_label == "build_state" } > skip + end + + def build_state_maps(data) index = {} index_variables = {} custom_fields = {} @@ -989,8 +1530,7 @@ def assign_data(data) end end - # Publish the fully built snapshot; the maps are never mutated after this. - @state = State.new(data, index, index_variables, custom_fields) + State.new(data, index, index_variables, custom_fields) end # Collector IDs are integers; integral floats and canonical decimal text @@ -1006,7 +1546,7 @@ def holdout_id(id) def set_data_failed(exception) @data_failed = exception @ready_error = exception - @state = State.new(ContextData.new, {}, {}, {}) + @state = @failed_state = State.new(ContextData.new, {}, {}, {}) @failed = true end @@ -1033,6 +1573,9 @@ def init_common(clock, config, data_provider, event_handler, event_logger, @assignment_cache = {} @holdout_assignments = nil @assignment_mutex = Mutex.new + @failed_marked = false + @exposing = {}.compare_by_identity + @exposure_condvar = ConditionVariable.new @assignments = {} @clock = clock.is_a?(String) ? Time.iso8601(clock) : clock @publish_delay = config.publish_delay @@ -1044,9 +1587,11 @@ def init_common(clock, config, data_provider, event_handler, event_logger, @audience_matcher = audience_matcher @environment = environment @closed = false - @closing = false + @sealing = 0 @failed = false @ready_error = nil + @sealed_by = nil + @building_threads = {} # System attributes (application/environment names from the client # config) seed the audience evaluation map. The collector already @@ -1069,7 +1614,9 @@ def init_common(clock, config, data_provider, event_handler, event_logger, @ready_condvar = ConditionVariable.new @queue_mutex = Mutex.new @publish_mutex = Mutex.new + @deferred_mutex = Mutex.new @close_pending = false + @close_requests = 0 set_units(config.units) if config.units set_attributes(config.attributes) if config.attributes @@ -1135,6 +1682,9 @@ def initialize @attrs_seq = 0 @holdouts = nil @matched_holdouts = 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 end end diff --git a/lib/context_data_result.rb b/lib/context_data_result.rb index 0edd2361..8258a4bc 100644 --- a/lib/context_data_result.rb +++ b/lib/context_data_result.rb @@ -3,23 +3,25 @@ # The immutable outcome of one context data fetch. Client#context_data returns # a new one per call, so concurrent fetches on a shared Client can't observe # each other's in-flight state. -class ContextDataResult - attr_reader :data_future, :exception, :promise +module Absmartly + class ContextDataResult + attr_reader :data_future, :exception, :promise - def self.failure(exception, promise = nil) - new(nil, exception, promise) - end + def self.failure(exception, promise = nil) + new(nil, exception, promise) + end - def initialize(data_future, exception = nil, promise = nil) - @data_future = data_future - @exception = exception - @promise = promise - freeze - end + def initialize(data_future, exception = nil, promise = nil) + @data_future = data_future + @exception = exception + @promise = promise + freeze + end - def success? - @exception.nil? && !@data_future.nil? - end + def success? + @exception.nil? && !@data_future.nil? + end - alias data data_future + alias data data_future + end end diff --git a/lib/context_event_handler.rb b/lib/context_event_handler.rb index 7582fc6d..8757196d 100644 --- a/lib/context_event_handler.rb +++ b/lib/context_event_handler.rb @@ -1,7 +1,8 @@ # frozen_string_literal: true -require_relative "context_publisher" - -# @deprecated Use ContextPublisher instead. -ContextEventHandler = ContextPublisher -Object.deprecate_constant :ContextEventHandler +class ContextEventHandler + # @interface method + def publish(context, event) + raise NotImplementedError.new("You must implement publish method.") + end +end diff --git a/lib/context_publisher.rb b/lib/context_publisher.rb index c328bdaa..e509127c 100644 --- a/lib/context_publisher.rb +++ b/lib/context_publisher.rb @@ -1,8 +1,9 @@ # frozen_string_literal: true -class ContextPublisher - # @interface method - def publish(context, event) - raise NotImplementedError.new("You must implement publish method.") - end +require_relative "context_event_handler" + +module Absmartly + # The name the other ABsmartly SDKs use for ContextEventHandler. Namespaced + # so it can't clash with an application's own ContextPublisher. + ContextPublisher = ::ContextEventHandler end diff --git a/lib/default_context_event_handler.rb b/lib/default_context_event_handler.rb index f3e6822c..caecf68e 100644 --- a/lib/default_context_event_handler.rb +++ b/lib/default_context_event_handler.rb @@ -1,7 +1,15 @@ # frozen_string_literal: true -require_relative "default_context_publisher" +require_relative "context_event_handler" -# @deprecated Use DefaultContextPublisher instead. -DefaultContextEventHandler = DefaultContextPublisher -Object.deprecate_constant :DefaultContextEventHandler +class DefaultContextEventHandler < ContextEventHandler + attr_accessor :client + + def initialize(client) + @client = client + end + + def publish(context, event) + @client.publish(event) + end +end diff --git a/lib/default_context_publisher.rb b/lib/default_context_publisher.rb index c6669066..1e60baec 100644 --- a/lib/default_context_publisher.rb +++ b/lib/default_context_publisher.rb @@ -1,15 +1,9 @@ # frozen_string_literal: true require_relative "context_publisher" +require_relative "default_context_event_handler" -class DefaultContextPublisher < ContextPublisher - attr_accessor :client - - def initialize(client) - @client = client - end - - def publish(context, event) - @client.publish(event) - end +module Absmartly + # The name the other ABsmartly SDKs use for DefaultContextEventHandler. + DefaultContextPublisher = ::DefaultContextEventHandler end diff --git a/lib/hashing.rb b/lib/hashing.rb index b5a657c0..e201336e 100644 --- a/lib/hashing.rb +++ b/lib/hashing.rb @@ -9,38 +9,19 @@ class Hashing # A lone surrogate written as a 3-byte sequence. ENCODED_SURROGATE = /\xED[\xA0-\xBF][\x80-\xBF]/n.freeze - # 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. + # 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. 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)) - 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 + base64_url_no_padding(Digest::MD5.digest(value.to_s.b)) 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. Characters outside the + # Returns the UTF-8 form of the unit's Unicode text (hash_unit keeps v1.3.0's + # raw bytes). 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/lib/json/experiment.rb b/lib/json/experiment.rb index bebc5155..4e0f4503 100644 --- a/lib/json/experiment.rb +++ b/lib/json/experiment.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require_relative "../string" require_relative "../type_utils" require_relative "experiment_application" require_relative "experiment_variant" diff --git a/lib/json_expr/expr_evaluator.rb b/lib/json_expr/expr_evaluator.rb index 09758bc0..7be74adf 100644 --- a/lib/json_expr/expr_evaluator.rb +++ b/lib/json_expr/expr_evaluator.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require_relative "../string" require_relative "../type_utils" require_relative "./evaluator" EMPTY_MAP = {} @@ -108,3 +109,11 @@ def compare(lhs, rhs) nil end end + +# Kept from v1.3.0, which defined it here; the SDK itself uses +# Absmartly::TypeUtils.wrap_array. +class Array + def self.wrap(object) + Absmartly::TypeUtils.wrap_array(object) + end +end diff --git a/lib/json_expr/json_expr.rb b/lib/json_expr/json_expr.rb index 24d50f75..d58ee323 100644 --- a/lib/json_expr/json_expr.rb +++ b/lib/json_expr/json_expr.rb @@ -38,11 +38,11 @@ def initialize "gte": GreaterThanOrEqualOperator.new, "lt": LessThanOperator.new, "lte": LessThanOrEqualOperator.new, - "semver_eq": SemverEqualsOperator.new, - "semver_gt": SemverGreaterThanOperator.new, - "semver_gte": SemverGreaterThanOrEqualOperator.new, - "semver_lt": SemverLessThanOperator.new, - "semver_lte": SemverLessThanOrEqualOperator.new + "semver_eq": Absmartly::SemverEqualsOperator.new, + "semver_gt": Absmartly::SemverGreaterThanOperator.new, + "semver_gte": Absmartly::SemverGreaterThanOrEqualOperator.new, + "semver_lt": Absmartly::SemverLessThanOperator.new, + "semver_lte": Absmartly::SemverLessThanOrEqualOperator.new } end diff --git a/lib/json_expr/operators/semver_operator.rb b/lib/json_expr/operators/semver_operator.rb index 0ab7adad..c8ce716b 100644 --- a/lib/json_expr/operators/semver_operator.rb +++ b/lib/json_expr/operators/semver_operator.rb @@ -3,13 +3,15 @@ require_relative "binary_operator" require_relative "../semver_comparator" -module SemverOperator - include BinaryOperator +module Absmartly + module SemverOperator + include BinaryOperator - def binary(evaluator, lhs, rhs) - result = SemverComparator.compare(evaluator, lhs, rhs) - return nil if result.nil? + def binary(evaluator, lhs, rhs) + result = Absmartly::SemverComparator.compare(evaluator, lhs, rhs) + return nil if result.nil? - compare_result(result) + compare_result(result) + end end end diff --git a/lib/json_expr/operators/semver_operators.rb b/lib/json_expr/operators/semver_operators.rb index 8c199d4e..c35f37b3 100644 --- a/lib/json_expr/operators/semver_operators.rb +++ b/lib/json_expr/operators/semver_operators.rb @@ -2,47 +2,49 @@ require_relative "semver_operator" -class SemverEqualsOperator - include SemverOperator - - private - def compare_result(result) - result.zero? - end -end - -class SemverGreaterThanOperator - include SemverOperator - - private - def compare_result(result) - result.positive? - end -end - -class SemverGreaterThanOrEqualOperator - include SemverOperator - - private - def compare_result(result) - result >= 0 - end -end - -class SemverLessThanOperator - include SemverOperator - - private - def compare_result(result) - result.negative? - end -end - -class SemverLessThanOrEqualOperator - include SemverOperator - - private - def compare_result(result) - result <= 0 - end +module Absmartly + class SemverEqualsOperator + include SemverOperator + + private + def compare_result(result) + result.zero? + end + end + + class SemverGreaterThanOperator + include SemverOperator + + private + def compare_result(result) + result.positive? + end + end + + class SemverGreaterThanOrEqualOperator + include SemverOperator + + private + def compare_result(result) + result >= 0 + end + end + + class SemverLessThanOperator + include SemverOperator + + private + def compare_result(result) + result.negative? + end + end + + class SemverLessThanOrEqualOperator + include SemverOperator + + private + def compare_result(result) + result <= 0 + end + end end diff --git a/lib/json_expr/semver_comparator.rb b/lib/json_expr/semver_comparator.rb index 6afad202..d85aacea 100644 --- a/lib/json_expr/semver_comparator.rb +++ b/lib/json_expr/semver_comparator.rb @@ -1,96 +1,98 @@ # frozen_string_literal: true # A port of the JavaScript SDK's versionCompare; keep the two in step. -module SemverComparator - NUMERIC_IDENTIFIER = /\A\d+\z/.freeze - FIXED_DIGITS = 15 - FIXED_SCALE = 10**FIXED_DIGITS - TRAILING_FIXED_ZEROS = /\.?0{0,15}\z/.freeze - - module_function - - def compare(evaluator, lhs, rhs) - lhs_str = to_version_string(evaluator, lhs) - rhs_str = to_version_string(evaluator, rhs) - return nil if lhs_str.nil? || rhs_str.nil? || lhs_str.empty? || rhs_str.empty? - - l = parse(lhs_str) - r = parse(rhs_str) - return nil if l.nil? || r.nil? - - [l[:parts].size, r[:parts].size].max.times do |i| - result = compare_identifiers(l[:parts][i] || "0", r[:parts][i] || "0") - return result unless result.zero? +module Absmartly + module SemverComparator + NUMERIC_IDENTIFIER = /\A\d+\z/.freeze + FIXED_DIGITS = 15 + FIXED_SCALE = 10**FIXED_DIGITS + TRAILING_FIXED_ZEROS = /\.?0{0,15}\z/.freeze + + module_function + + def compare(evaluator, lhs, rhs) + lhs_str = to_version_string(evaluator, lhs) + rhs_str = to_version_string(evaluator, rhs) + return nil if lhs_str.nil? || rhs_str.nil? || lhs_str.empty? || rhs_str.empty? + + l = parse(lhs_str) + r = parse(rhs_str) + return nil if l.nil? || r.nil? + + [l[:parts].size, r[:parts].size].max.times do |i| + result = compare_identifiers(l[:parts][i] || "0", r[:parts][i] || "0") + return result unless result.zero? + end + + return 0 if l[:pre_release].empty? && r[:pre_release].empty? + return 1 if l[:pre_release].empty? + return -1 if r[:pre_release].empty? + + l_pre = l[:pre_release].split(".", -1) + r_pre = r[:pre_release].split(".", -1) + [l_pre.size, r_pre.size].max.times do |i| + return -1 if i >= l_pre.size + return 1 if i >= r_pre.size + + result = compare_identifiers(l_pre[i], r_pre[i]) + return result unless result.zero? + end + 0 end - return 0 if l[:pre_release].empty? && r[:pre_release].empty? - return 1 if l[:pre_release].empty? - return -1 if r[:pre_release].empty? + # Numbers are converted as JavaScript's stringConvert does, + # x.toFixed(15) with trailing zeros trimmed, so 1.0000000000000002 is "1". + # The general string_convert is left alone for the other operators. + def to_version_string(evaluator, value) + return evaluator.string_convert(value) unless value.is_a?(Numeric) - l_pre = l[:pre_release].split(".", -1) - r_pre = r[:pre_release].split(".", -1) - [l_pre.size, r_pre.size].max.times do |i| - return -1 if i >= l_pre.size - return 1 if i >= r_pre.size - - result = compare_identifiers(l_pre[i], r_pre[i]) - return result unless result.zero? + to_fixed(value.to_f).sub(TRAILING_FIXED_ZEROS, "") end - 0 - end - - # Numbers are converted as JavaScript's stringConvert does, - # x.toFixed(15) with trailing zeros trimmed, so 1.0000000000000002 is "1". - # The general string_convert is left alone for the other operators. - def to_version_string(evaluator, value) - return evaluator.string_convert(value) unless value.is_a?(Numeric) - to_fixed(value.to_f).sub(TRAILING_FIXED_ZEROS, "") - end + # Number.prototype.toFixed(15): the exact binary value rounded half up, + # or the shortest round-trip text in exponent form from 1e21 up. + def to_fixed(x) + return x.to_s if x.nan? || x.infinite? + return x.to_s.sub(/\.0(?=e)/, "") if x.abs >= 1e21 - # Number.prototype.toFixed(15): the exact binary value rounded half up, - # or the shortest round-trip text in exponent form from 1e21 up. - def to_fixed(x) - return x.to_s if x.nan? || x.infinite? - return x.to_s.sub(/\.0(?=e)/, "") if x.abs >= 1e21 + scaled = (x.abs.to_r * FIXED_SCALE).round(half: :up) + int, frac = scaled.divmod(FIXED_SCALE) + "#{x.negative? ? '-' : ''}#{int}.#{frac.to_s.rjust(FIXED_DIGITS, '0')}" + end - scaled = (x.abs.to_r * FIXED_SCALE).round(half: :up) - int, frac = scaled.divmod(FIXED_SCALE) - "#{x.negative? ? '-' : ''}#{int}.#{frac.to_s.rjust(FIXED_DIGITS, '0')}" - end + def parse(version) + v = version + v = v[1..] if v.start_with?("v", "V") + plus = v.index("+") + v = v[0, plus] unless plus.nil? + return nil if v.empty? - def parse(version) - v = version - v = v[1..] if v.start_with?("v", "V") - plus = v.index("+") - v = v[0, plus] unless plus.nil? - return nil if v.empty? + core, *pre_release = v.split("-", -1) + return nil if core.nil? || core.empty? - core, *pre_release = v.split("-", -1) - return nil if core.nil? || core.empty? + { parts: core.split(".", -1), pre_release: pre_release.join("-") } + end - { parts: core.split(".", -1), pre_release: pre_release.join("-") } - end + def compare_identifiers(a, b) + a_num = a.match?(NUMERIC_IDENTIFIER) + b_num = b.match?(NUMERIC_IDENTIFIER) - def compare_identifiers(a, b) - a_num = a.match?(NUMERIC_IDENTIFIER) - b_num = b.match?(NUMERIC_IDENTIFIER) + if a_num && b_num + a_norm = strip_leading_zeros(a) + b_norm = strip_leading_zeros(b) + return a_norm.size <=> b_norm.size unless a_norm.size == b_norm.size - if a_num && b_num - a_norm = strip_leading_zeros(a) - b_norm = strip_leading_zeros(b) - return a_norm.size <=> b_norm.size unless a_norm.size == b_norm.size + return a_norm <=> b_norm + end + return -1 if a_num + return 1 if b_num - return a_norm <=> b_norm + a <=> b end - return -1 if a_num - return 1 if b_num - a <=> b - end - - def strip_leading_zeros(s) - stripped = s.sub(/\A0+/, "") - stripped.empty? ? "0" : stripped + def strip_leading_zeros(s) + stripped = s.sub(/\A0+/, "") + stripped.empty? ? "0" : stripped + end end end diff --git a/lib/publish_error.rb b/lib/publish_error.rb index 37838020..a332b63a 100644 --- a/lib/publish_error.rb +++ b/lib/publish_error.rb @@ -5,5 +5,7 @@ # recover from an operational failure with an ordinary `rescue => e` / # `rescue StandardError` around close, finalize or publish, rather than being # forced to rescue Ruby's base Exception. -class PublishError < StandardError +module Absmartly + class PublishError < StandardError + end end diff --git a/lib/scheduled_thread_pool_executor.rb b/lib/scheduled_thread_pool_executor.rb index 761313bb..7cac8223 100644 --- a/lib/scheduled_thread_pool_executor.rb +++ b/lib/scheduled_thread_pool_executor.rb @@ -1,10 +1,18 @@ # frozen_string_literal: true -class ScheduledThreadPoolExecutor +require_relative "audience_deserializer" + +class ScheduledThreadPoolExecutor < AudienceDeserializer + attr_accessor :log, :reader + def initialize(timer = 1) @timer = timer end + def deserialize(bytes, offset, length) + @reader.read_value(bytes, offset, length) + end + def execute(&block) block.call if block end diff --git a/spec/a_b_smartly_config_spec.rb b/spec/a_b_smartly_config_spec.rb index c790f3c3..bc718554 100644 --- a/spec/a_b_smartly_config_spec.rb +++ b/spec/a_b_smartly_config_spec.rb @@ -17,7 +17,7 @@ end it ".context_event_handler" do - handler = ContextPublisher.new + handler = Absmartly::ContextPublisher.new config = described_class.create config.context_event_handler = handler expect(handler).to eq(config.context_event_handler) @@ -45,7 +45,7 @@ end it "set all" do - handler = ContextPublisher.new + handler = Absmartly::ContextPublisher.new provider = ContextDataProvider.new parser = VariableParser.new scheduler = ScheduledExecutorService.new diff --git a/spec/absmartly_spec.rb b/spec/absmartly_spec.rb index 7190bb05..12089742 100644 --- a/spec/absmartly_spec.rb +++ b/spec/absmartly_spec.rb @@ -139,7 +139,7 @@ def clear let(:publish_future) { OpenStruct.new(success?: true) } let(:event_handler) do - ev = instance_double(ContextPublisher) + ev = instance_double(Absmartly::ContextPublisher) allow(ev).to receive(:publish).and_return(publish_future) ev end diff --git a/spec/audience_matcher_rules_spec.rb b/spec/audience_matcher_rules_spec.rb index 032bb59f..f4431f2e 100644 --- a/spec/audience_matcher_rules_spec.rb +++ b/spec/audience_matcher_rules_spec.rb @@ -130,6 +130,12 @@ def split_of(*fractions) expect(evaluate([split(".5/99.5")])).to eq(split_of(0.005, 0.995)) end + it "skips the ECMAScript white space before a split value, and nothing else" do + expect(evaluate([split("\uFEFF50/\u00A050")])).to eq(split_of(0.5, 0.5)) + expect(evaluate([split("\u202850/\u300050")])).to eq(split_of(0.5, 0.5)) + expect(evaluate([split("\u008550/50"), assign(2)])).to eq(assigned(2)) + end + it "skips splits that are not a string or have invalid values" do expect(evaluate([split(nil), assign(2)])).to eq(assigned(2)) expect(evaluate([split([50, 50]), assign(2)])).to eq(assigned(2)) diff --git a/spec/backwards_compatibility_spec.rb b/spec/backwards_compatibility_spec.rb index 7218d969..440f304e 100644 --- a/spec/backwards_compatibility_spec.rb +++ b/spec/backwards_compatibility_spec.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require "json" require "open3" require "rbconfig" require "a_b_smartly" @@ -20,13 +21,24 @@ def run_ruby(script) Open3.capture3(RbConfig.ruby, "-W:no-deprecated", "-I", lib, "-e", script) end + # Fiber.current and Fiber#alive? need require "fiber" before Ruby 3.1. + # A dependency (logger) may load it, but the library must not rely on that. + it "requires fiber itself where it uses Fiber.current" do + lib = File.expand_path("../lib", __dir__) + users = Dir[File.join(lib, "**/*.rb")].select { |f| File.read(f, encoding: "UTF-8").match?(/Fiber\.current|\.alive\?/) } + expect(users).not_to be_empty + users.each do |file| + expect(File.read(file, encoding: "UTF-8")).to match(/^require "fiber"$/), "#{file} uses Fiber.current without require \"fiber\"" + end + end + it "defines the public v1.3.0 classes after only require \"absmartly\"" do out, err, status = run_ruby(<<~RUBY) require "absmartly" class MyPublisher < ContextEventHandler def publish(context, event); end end - p [MyPublisher.ancestors.include?(ContextPublisher), DefaultContextEventHandler == DefaultContextPublisher] + p [MyPublisher.ancestors.include?(Absmartly::ContextPublisher), DefaultContextEventHandler == Absmartly::DefaultContextPublisher] RUBY expect([out, status.success?]).to eq(["[true, true]\n", true]), err end @@ -42,11 +54,93 @@ module TypeUtils; end expect([out, status.success?]).to eq(["[Module, Object, [], true]\n", true]), err end - it "ContextEventHandler is a deprecated alias for ContextPublisher" do + # The top-level constants the SDK's own files define after `require + # "absmartly"`, exactly as the published 1.3.0 gem defined them. Additions + # live under Absmartly so they can't clash with an application's classes; + # ContextDataResult and PublishError were top-level only on unreleased main. + V1_3_0_TOP_LEVEL = %i[ + ABSmartly ABSmartlyConfig Absmartly AndCombinator Assignment Attribute AudienceDeserializer AudienceMatcher + BinaryOperator BooleanCombinator Client ClientConfig Context ContextConfig ContextCustomFieldValues ContextData + ContextDataDeserializer ContextDataProvider ContextEventHandler ContextEventLogger ContextEventSerializer + CustomFieldValue DefaultAudienceDeserializer DefaultContextDataDeserializer DefaultContextDataProvider + DefaultContextEventHandler DefaultContextEventSerializer DefaultHttpClient DefaultHttpClientConfig + DefaultVariableParser EMPTY_LIST EMPTY_MAP EqualsOperator Evaluator Experiment ExperimentApplication + ExperimentVariables ExperimentVariant Exposure ExprEvaluator GoalAchievement GreaterThanOperator + GreaterThanOrEqualOperator Hashing HttpClient IllegalStateException InOperator JsonExpr LessThanOperator + LessThanOrEqualOperator MatchOperator NilOperator NotOperator OrCombinator PublishEvent + ScheduledThreadPoolExecutor UnaryOperator Unit ValueOperator VarOperator VariableParser VariantAssigner + ].freeze + + # spec/compat/top_level_surface.rb loads the SDK and drives its public entry + # points against a local collector (reads, peeks, rules, holdouts, custom + # fields, track, accepted and rejected publishes, refresh, overrides, async + # and pre-fetched contexts, the Absmartly module API, a failed fetch, + # finalize, close). In both load orders it promises, from require through + # that use: + # - top-level constants: exactly 1.3.0's, public or private, none added by use; + # - no SDK addition reachable at top level by name; + # - methods lib defines on classes it doesn't own: exactly 1.3.0's four + # (aliases of built-ins are checked on the core classes the script lists); + # - no SDK module in a core class's ancestors, Object's or Kernel's; + # - an application's same-named classes still resolve as before, unchanged. + %w[sdk_first app_first].each do |mode| + it "keeps the published 1.3.0 top-level surface through real use (#{mode.tr("_", " ")})" do + lib = File.expand_path("../lib", __dir__) + script = File.expand_path("compat/top_level_surface.rb", __dir__) + command = [RbConfig.ruby, "-W:no-deprecated", "-I", lib, script, lib, mode, *V1_3_0_TOP_LEVEL.map(&:to_s)] + out = err = status = nil + Open3.popen3(*command) do |stdin, stdout, stderr, wait| + stdin.close + readers = [Thread.new { stdout.read }, Thread.new { stderr.read }] + unless wait.join(60) + Process.kill("KILL", wait.pid) + raise "top_level_surface.rb did not finish within 60s" + end + out, err = readers.map(&:value) + status = wait.value + end + expect(status.success?).to be(true), err + report = JSON.parse(out.lines.last) + expect(report).to eq( + "sdk_owned" => V1_3_0_TOP_LEVEL.map(&:to_s).sort, "unexpected" => [], "missing" => [], + "added_by_use" => [], "private_top_level_added" => [], "ancestors_changed" => false, + "foreign_methods_from_lib" => ["Array.wrap", "String#compare_to", "String#get_char", "String#underscore"], + "sdk_mixins" => [], "reachable" => [], "app_intact" => true, "working" => true + ) + end + end + + it "loads next to application classes named like the SDK's additions without replacing them" do + out, err, status = run_ruby(<<~RUBY) + class PublishError < RuntimeError; end + class SemverComparator; end + class ContextDataResult; end + require "absmartly" + class Base; end + class ContextPublisher < Base + def publish(*); :mine; end + end + class DefaultContextPublisher + def publish(*); :mine_too; end + end + p [PublishError.superclass, SemverComparator.class, ContextPublisher.superclass, + ContextPublisher == ContextEventHandler, DefaultContextPublisher.superclass, + DefaultContextEventHandler.new(Object.new).respond_to?(:publish) && + DefaultContextEventHandler.instance_method(:publish).owner, + Absmartly::PublishError.superclass, + ABSmartly.new("https://x/v1", api_key: "k", application: "a", environment: "e") + .context_event_handler.class] + RUBY + expect([out, status.success?]) + .to eq(["[RuntimeError, Class, Base, false, Object, DefaultContextEventHandler, StandardError, DefaultContextEventHandler]\n", + true]), err + end + + it "ContextEventHandler is still the v1.3.0 class, aliased as Absmartly::ContextPublisher without a warning" do original = Warning[:deprecated] Warning[:deprecated] = true - expect { expect(Object.const_get(:ContextEventHandler)).to eq(ContextPublisher) } - .to output(/ContextEventHandler is deprecated/).to_stderr + expect { expect(Absmartly::ContextPublisher).to eq(ContextEventHandler) }.not_to output.to_stderr + expect(ContextEventHandler.name).to eq("ContextEventHandler") ensure Warning[:deprecated] = original end @@ -78,6 +172,29 @@ module TypeUtils; end expect(experiment.custom_field_values).to eq([CustomFieldValue.new("country", "US", "string")]) end + it "parses custom field values whose type is given as a Symbol, as in v1.3.0" do + out, err, status = run_ruby(<<~RUBY) + require "absmartly" + data = ContextData.new([{ id: 1, name: "exp", unitType: "session_id", iteration: 1, split: [1], + trafficSplit: [1], fullOnVariant: 0, seedHi: 0, seedLo: 0, + trafficSeedHi: 0, trafficSeedLo: 0, + variants: [{ name: "A", config: nil }], + customFieldValues: [{ name: "j", value: '{"a":1}', type: :json }, + { name: "n", value: "7", type: :number }, + { name: "b", value: "true", type: :boolean }] }]) + config = ContextConfig.create + config.set_unit("session_id", "u1") + context = Context.create(Time.at(0), config, Struct.new(:data_future, :success?).new(data, true), nil, + nil, nil, DefaultVariableParser.new, + AudienceMatcher.new(DefaultAudienceDeserializer.new)) + print Marshal.dump([context.custom_field_value("exp", "j"), context.custom_field_value("exp", "n"), + context.custom_field_value("exp", "b")]).unpack1("H*") + RUBY + + expect(status).to be_success, err + expect(Marshal.load([out].pack("H*"))).to eq([{ a: 1 }, 7, true]) + end + it "prefers the symbol key when a nested object has both key styles" do experiment = Experiment.new(variants: [{ name: "sym", "name" => "str", config: nil }]) @@ -88,11 +205,12 @@ module TypeUtils; end expect(experiment.variants.first.name).to be_nil end - it "DefaultContextEventHandler is a deprecated alias for DefaultContextPublisher" do + it "DefaultContextEventHandler is still the v1.3.0 class, aliased as Absmartly::DefaultContextPublisher without a warning" do original = Warning[:deprecated] Warning[:deprecated] = true - expect { expect(Object.const_get(:DefaultContextEventHandler)).to eq(DefaultContextPublisher) } - .to output(/DefaultContextEventHandler is deprecated/).to_stderr + expect { expect(Absmartly::DefaultContextPublisher).to eq(DefaultContextEventHandler) }.not_to output.to_stderr + expect(DefaultContextEventHandler.name).to eq("DefaultContextEventHandler") + expect(DefaultContextEventHandler.superclass).to eq(ContextEventHandler) ensure Warning[:deprecated] = original end @@ -105,7 +223,7 @@ module TypeUtils; end config = ABSmartlyConfig.create config.client = client expect(ABSmartly.create(config).context_event_handler).to be_a(Object.const_get(:DefaultContextEventHandler)) - expect(@handler).to be_a(DefaultContextPublisher) + expect(@handler).to be_a(Absmartly::DefaultContextPublisher) ensure Warning[:deprecated] = original end @@ -119,7 +237,7 @@ module TypeUtils; end it "does not load ostruct, which is not a default gem from Ruby 3.5" do lib = File.expand_path("../lib", __dir__) - expect(Dir[File.join(lib, "**/*.rb")].grep_v(/_spec/).select { |f| File.read(f).match?(/require ["']ostruct["']|OpenStruct/) }) + expect(Dir[File.join(lib, "**/*.rb")].grep_v(/_spec/).select { |f| File.read(f, encoding: "UTF-8").match?(/require ["']ostruct["']|OpenStruct/) }) .to be_empty end diff --git a/spec/client_spec.rb b/spec/client_spec.rb index 3e3903df..99d2e58b 100644 --- a/spec/client_spec.rb +++ b/spec/client_spec.rb @@ -60,6 +60,18 @@ expect(client.headers[:"X-Application-Version"]).to eq("0") end + it "takes the X-Agent version from Absmartly::VERSION, not a fixed string" do + stub_const("Absmartly::VERSION", "9.8.7") + config = ClientConfig.create + config.endpoint = "https://localhost/v1" + config.api_key = "test-api-key" + config.application = "website" + config.environment = "dev" + + expect(Client.create(config, instance_double(DefaultHttpClient)).headers[:"X-Agent"]) + .to eq("absmartly-ruby-sdk/9.8.7") + end + it "create with defaults" do config = ClientConfig.create config.endpoint = "https://localhost/v1" @@ -336,7 +348,7 @@ .and_return(response_future) publish_future = client.publish(event) actual = publish_future - expect(actual).to be_a(PublishError) + expect(actual).to be_a(Absmartly::PublishError) expect(actual).to be_a(StandardError) expect(actual.message).to eq("FAILED") diff --git a/spec/compat/top_level_surface.rb b/spec/compat/top_level_surface.rb new file mode 100644 index 00000000..8119ac6a --- /dev/null +++ b/spec/compat/top_level_surface.rb @@ -0,0 +1,277 @@ +# frozen_string_literal: true + +# Run in a fresh process: ruby -I top_level_surface.rb +# +# Loads the SDK and drives every public entry point against a local fake +# collector, then prints one JSON line describing the top-level surface. In +# app_first mode the application has already defined a class for every name +# the SDK keeps under Absmartly; those must come through untouched. +require "json" +require "socket" + +# The real path: Ruby reports where constants and methods were defined that way. +lib = File.realpath(ARGV.shift) +mode = ARGV.shift +expected = ARGV.map(&:to_sym) +app_first = mode == "app_first" + +# The names 1.4.0 adds under Absmartly, which 1.3.0 never defined at top level. +ADDITIONS = %i[ContextDataResult ContextPublisher DefaultContextPublisher PublishError SemverComparator + SemverEqualsOperator SemverGreaterThanOperator SemverGreaterThanOrEqualOperator + SemverLessThanOperator SemverLessThanOrEqualOperator SemverOperator TypeUtils].freeze + +def fingerprint(klass) + own = klass.instance_methods(false) + klass.private_instance_methods(false) + [own.sort.map { |name| [name, klass.instance_method(name).source_location, klass.instance_method(name).original_name] }, + klass.singleton_methods.sort, klass.constants.sort, klass.ancestors.take_while { |mod| mod != Object }, + klass.singleton_class.ancestors.take_while { |mod| mod != Object.singleton_class }] +end + +app_classes = {} +if app_first + ADDITIONS.each do |name| + klass = Object.const_set(name, Class.new(RuntimeError) { def app_marker; :app; end }) + app_classes[name] = [klass, fingerprint(klass)] + end +end + +payload = { + experiments: [{ id: 1, name: "exp", unitType: "session_id", iteration: 1, seedHi: 1, seedLo: 2, + split: [0.0, 1.0], trafficSeedHi: 3, trafficSeedLo: 4, trafficSplit: [0, 1], + fullOnVariant: 0, applications: [{ name: "a" }], + audience: '{"filter":[{"semver_gt":[{"var":"v"},{"value":"1.0.0"}]}]}', + customFieldValues: [{ name: "f", value: "x", type: "string" }], + variants: [{ name: "A", config: nil }, { name: "B", config: '{"x":1}' }] }, + # 1.4.0's assignment rules and holdouts run too: a split rule and a covering holdout. + { id: 2, name: "ruled", unitType: "session_id", iteration: 1, seedHi: 1, seedLo: 2, + split: [0.5, 0.5], trafficSeedHi: 3, trafficSeedLo: 4, trafficSplit: [0, 1], + fullOnVariant: 0, applications: [{ name: "a" }], holdoutIds: [9], + assignmentRules: JSON.generate(rules: [{ name: "split", type: "split", environments: [], + conditions: { and: [{ eq: [{ var: "v" }, { value: "2.0.0" }] }] }, + percentages: "0/100" }]), + variants: [{ name: "A", config: '{"y":0}' }, { name: "B", config: '{"y":1}' }] }], + holdouts: [{ id: 9, name: "holdout", unitType: "session_id", iteration: 1, seedHi: 5, seedLo: 6, + split: [0.0, 1.0], trafficSeedHi: 0, trafficSeedLo: 0, trafficSplit: [0.0, 1.0], + fullOnVariant: 0, applications: [], holdoutType: "full", + variants: [{ name: "A", config: nil }, { name: "B", config: nil }] }] +}.to_json +server = TCPServer.new("127.0.0.1", 0) +port = server.addr[1] +put_status = 200 +requests = Hash.new(0) +Thread.new do + loop do + Thread.new(server.accept) do |client| + while (line = client.gets) + method = line.split.first + requests[method] += 1 + length = 0 + while (header = client.gets) && header != "\r\n" + length = header.split(":", 2)[1].to_i if header =~ /\Acontent-length:/i + end + client.read(length) if length.positive? + status = method == "PUT" ? put_status : 200 + body = method == "GET" ? payload : "{}" + client.write("HTTP/1.1 #{status} X\r\nContent-Type: application/json\r\n" \ + "Content-Length: #{body.bytesize}\r\n\r\n#{body}") + end + ensure + client.close + end + end +end + +# Core classes the SDK could plausibly extend or mix into. Their method lists +# before require catch an alias of a built-in, which has no source location. +EXTENDED = [Object, Kernel, BasicObject, Module, Class, String, Symbol, Array, Hash, Integer, Float, Numeric, + Comparable, Enumerable, NilClass, TrueClass, FalseClass, Time].freeze +# Private top-level constants: Ruby lists only public ones, so probe every +# constant-like symbol Ruby knows; const_defined? sees private ones too. +def private_top_level + public_names = Object.constants + Symbol.all_symbols.select do |name| + name.match?(/\A[A-Z]\w*\z/) && !public_names.include?(name) && Object.const_defined?(name, false) + end +end +method_lists = lambda do + EXTENDED.to_h do |mod| + [mod, [mod.instance_methods(false) + mod.private_instance_methods(false), + mod.singleton_class.instance_methods(false) + mod.singleton_class.private_instance_methods(false)]] + end +end +# Each core class's public and private method names, own and inherited: a +# visibility change on a built-in (public :puts) moves a name between them. +visibility = -> { EXTENDED.to_h { |mod| [mod, [mod.public_instance_methods.sort, mod.private_instance_methods.sort]] } } +visibility_before = visibility.call +ancestors_before = EXTENDED.to_h { |mod| [mod, [mod.ancestors, mod.singleton_class.ancestors]] } +methods_before = method_lists.call +before = Object.constants +private_before = private_top_level +object_ancestors_before = Object.ancestors.dup +kernel_ancestors_before = Kernel.ancestors.dup +require "absmartly" +after_require = Object.constants +private_after_require = private_top_level +# A constant counts as the SDK's if it is located in lib or was eval'd. No +# location means it was defined in C, and the SDK has no C code. +sdk_owned = (after_require - before).select do |name| + path = Object.const_source_location(name)&.first + path.is_a?(String) && (path.start_with?(lib) || !path.start_with?("/")) +end +# Absmartly is 1.3.0's own module (Absmartly::VERSION); bundler's gemspec may +# have loaded version.rb before this script, from another checkout. +sdk_owned |= [:Absmartly] if Object.const_defined?(:Absmartly, false) && Absmartly.const_defined?(:VERSION, false) + +working = [] +sdk = ABSmartly.new("http://127.0.0.1:#{port}/v1", api_key: "k", application: "a", environment: "e") +config = ContextConfig.create +config.set_unit(:session_id, "u1") +context = sdk.create_context(config) +context.wait_until_ready +working << (context.ready? && !context.failed?) +context.set_attribute("v", "2.0.0") +working << (context.treatment("exp") == 1) +working << (context.variable_value("x", 0) == 1) +working << (context.peek_treatment("exp") == 1) +working << (context.peek_variable_value("x", 0) == 1) +working << (context.variable_keys[:x] == "exp") +working << context.custom_field_keys.include?("f") +working << (context.custom_field_value("exp", "f") == "x") +working << (context.treatment("ruled") == 1) +working << (context.variable_value("y", 0) == 1) +context.track("goal", { a: 1 }) +context.publish +put_status = 503 +context.track("rejected", {}) +begin + context.publish +rescue StandardError + nil +end +put_status = 200 +context.refresh +context.set_override("exp", 0) +context.set_custom_assignment("exp", 0) +async = sdk.create_context_async(config) +async.wait_until_ready +working << (async.treatment("exp") == 1) +async.close +with = sdk.create_context_with(config, sdk.context_data) +working << (with.treatment("exp") == 1) +with.close +context.finalize +context.close +Absmartly.configure_client do |client_config| + client_config.endpoint = "http://127.0.0.1:#{port}/v1" + client_config.api_key = "k" + client_config.application = "a" + client_config.environment = "e" +end +module_context = Absmartly.create_context(Absmartly.create_context_config.tap { |c| c.set_unit(:session_id, "u2") }) +module_context.wait_until_ready +working << module_context.ready? +module_context.close +unreachable = ABSmartly.new("http://127.0.0.1:1/v1", api_key: "k", application: "a", environment: "e", retries: 0) +failed = unreachable.create_context(config) +failed.wait_until_ready +working << failed.failed? +failed.close + +reachable = ADDITIONS.select do |name| + resolved = begin + TOPLEVEL_BINDING.eval(name.to_s) + rescue NameError + nil + end + app_first ? resolved.equal?(Absmartly.const_get(name)) : (Object.const_defined?(name) || !resolved.nil?) +end +# Ruby's own libraries (pp, json) extend Object; a module that defines +# methods in lib, or any change to Kernel's ancestors, is the SDK's doing. +new_object_ancestors = Object.ancestors - object_ancestors_before +ancestors_changed = Kernel.ancestors != kernel_ancestors_before || new_object_ancestors.any? do |mod| + (mod.instance_methods(false) + mod.private_instance_methods(false)).any? do |method| + mod.instance_method(method).source_location&.first.to_s.start_with?(lib) + end || mod == Absmartly +end +# Methods lib defines on modules it does not own (core classes, gems). +# 1.3.0 already added Array.wrap and String#compare_to, #get_char and +# #underscore; anything beyond those is new. +sdk_module = lambda do |mod| + root = mod.name.to_s.split("::").first + root.nil? || root.empty? || root == "Absmartly" || sdk_owned.include?(root.to_sym) +end +foreign_methods_from_lib = [] +ObjectSpace.each_object(Module) do |mod| + next if sdk_module.call(mod) + + [[mod, "#"], [mod.singleton_class, "."]].each do |owner, separator| + (owner.instance_methods(false) + owner.private_instance_methods(false)).each do |method| + location = owner.instance_method(method).source_location&.first.to_s + # An eval'd definition counts as the SDK's when lib called the eval + # ("(eval at :)"; Ruby's json library defines some this way). + next unless location.start_with?(lib) || location.start_with?("(eval at #{lib}") + + foreign_methods_from_lib << "#{mod}#{separator}#{method}" + end + end +end +# Aliases of built-in methods added since before require, on the classes the +# SDK could plausibly extend (an alias reports its original's location). +methods_after = method_lists.call +EXTENDED.each do |mod| + [[mod, "#", 0], [mod.singleton_class, ".", 1]].each do |owner, separator, index| + (methods_after[mod][index] - methods_before[mod][index]).each do |method| + unbound = owner.instance_method(method) + # An alias keeps its original's name, wherever the original is defined + # (C, or Ruby's prelude); a C extension method such as + # date's Time#to_date, loaded by a dependency, is its own original. + next if unbound.original_name == method + next if unbound.source_location && unbound.source_location.first.to_s.start_with?("/") && + !unbound.source_location.first.to_s.start_with?(lib) + + foreign_methods_from_lib << "#{mod}#{separator}#{method}" + end + end +end +visibility_after = visibility.call +EXTENDED.each do |mod| + public_before, private_before_names = visibility_before[mod] + public_after, private_after_names = visibility_after[mod] + ((public_after & private_before_names) + (private_after_names & public_before)).each do |method| + foreign_methods_from_lib << "#{mod}##{method} (visibility)" + end +end +# No SDK module mixed into a core class (an include adds no method there). +# Any module added to a core class's ancestors since before require, named +# or anonymous, that is the SDK's: named under it, or defining methods in lib. +sdk_mixins = EXTENDED.flat_map do |klass| + added = (klass.ancestors - ancestors_before[klass][0]) + (klass.singleton_class.ancestors - ancestors_before[klass][1]) + added.select do |mod| + (mod.name && sdk_module.call(mod)) || + (mod.instance_methods(false) + mod.private_instance_methods(false)).any? do |method| + location = mod.instance_method(method).source_location&.first.to_s + location.start_with?(lib) || location.start_with?("(eval at #{lib}") + end + end.map { |mod| "#{klass}<#{mod.name || "anonymous"}" } +end +# Resolved as application code does, by bare name at top level. +app_intact = app_classes.all? do |name, (klass, print)| + TOPLEVEL_BINDING.eval(name.to_s).equal?(klass) && fingerprint(klass) == print +rescue NameError + false +end + +puts JSON.generate( + sdk_owned: sdk_owned.sort, + unexpected: (sdk_owned - expected).sort, + # After use too: a constant 1.3.0 had must still resolve at the end. + missing: ((expected - sdk_owned) | expected.reject { |name| Object.const_defined?(name, false) }).sort, + added_by_use: (Object.constants - after_require).sort, + private_top_level_added: ((private_after_require - private_before) | (private_top_level - private_after_require)).sort, + ancestors_changed: ancestors_changed, + foreign_methods_from_lib: foreign_methods_from_lib.sort.uniq, + sdk_mixins: sdk_mixins.uniq, + reachable: reachable, + app_intact: app_intact, + working: working.all? && requests["GET"] >= 4 && requests["PUT"] >= 2 +) diff --git a/spec/compat/v1_3_0_consumer.rb b/spec/compat/v1_3_0_consumer.rb new file mode 100644 index 00000000..f0632358 --- /dev/null +++ b/spec/compat/v1_3_0_consumer.rb @@ -0,0 +1,147 @@ +# frozen_string_literal: true + +# A customer app written against absmartly-sdk 1.3.0's README and public classes. +# Run in a fresh process by spec/compat_v1_3_0_spec.rb; keep it in 1.3.0's API only. +require "absmartly" +require "json" + +results = [] +check = ->(name, cond) { results << [name, cond ? "ok" : "FAIL"] } + +# Extension points subclassed the way 1.3.0 allowed. +class MyEventLogger < ContextEventLogger + attr_reader :events + def initialize; @events = []; end + def handle_event(event, data) + case event + when EVENT_TYPE::EXPOSURE, EVENT_TYPE::GOAL, EVENT_TYPE::ERROR, EVENT_TYPE::PUBLISH, + EVENT_TYPE::READY, EVENT_TYPE::REFRESH, EVENT_TYPE::CLOSE + @events << event + end + end +end +class MyHandler < ContextEventHandler + attr_reader :n + def publish(context, event); @n = (@n || 0) + 1; nil; end +end +class MyDefaultHandler < DefaultContextEventHandler; end +class MyProvider < ContextDataProvider + def context_data + raw = { experiments: [{ id: 1, name: "exp_test_experiment", unitType: "session_id", iteration: 1, 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: nil }, { name: "B", config: '{"button.color":"red"}' }], + audienceStrict: false, audience: nil }] }.to_json + Struct.new(:data_future) { def success?; true; end }.new(DefaultContextDataDeserializer.new.deserialize(raw, 0, raw.size)) + end +end +class MyParser < VariableParser + def parse(context, experiment_name, variant_name, config); JSON.parse(config, symbolize_names: true); end +end +class MyAudienceDeserializer < AudienceDeserializer + def deserialize(bytes, offset, length); JSON.parse(bytes, symbolize_names: true); end +end +class MyExecutor < ScheduledThreadPoolExecutor; end + +check.("DefaultContextEventHandler < ContextEventHandler", DefaultContextEventHandler.superclass == ContextEventHandler) +check.("ScheduledThreadPoolExecutor < AudienceDeserializer", ScheduledThreadPoolExecutor.superclass == AudienceDeserializer) +check.("core ext Array.wrap", Array.wrap(nil) == [] && Array.wrap(1) == [1]) +check.("core ext String#underscore/compare_to", "FooBar".underscore == "foo_bar" && "a".compare_to("b") < 0) +check.("Absmartly::Error", Absmartly::Error.ancestors.include?(StandardError)) + +# README: global configuration. +Absmartly.configure_client do |config| + config.endpoint = "https://your-company.absmartly.io/v1" + config.api_key = "YOUR-API-KEY" + config.application = "website" + config.environment = "development" + config.connect_timeout = 3.0 + config.connection_request_timeout = 3.0 + config.retry_interval = 0.5 + config.max_retries = 5 + config.event_logger = MyEventLogger.new +end +check.("Absmartly.create_context_config", Absmartly.create_context_config.is_a?(ContextConfig)) + +# README: explicit client config. +client_config = ClientConfig.new(endpoint: "https://your-company.absmartly.io/v1", api_key: "YOUR-API-KEY", + application: "website", environment: "development") +sdk_config = ABSmartlyConfig.create +sdk_config.client = Client.create(client_config) +check.("Client#headers X-Agent prefix", sdk_config.client.headers[:"X-Agent"].start_with?("absmartly-ruby-sdk")) +check.("Absmartly.create (global config)", Absmartly.create.is_a?(ABSmartly)) +sdk = ABSmartly.create(sdk_config) +check.("ABSmartly.create", sdk.is_a?(ABSmartly)) +check.("default handler is DefaultContextEventHandler", ABSmartly.create(sdk_config).context_event_handler.instance_of?(DefaultContextEventHandler)) + +logger = MyEventLogger.new +handler = MyHandler.new +cfg = ABSmartlyConfig.create +cfg.context_data_provider = MyProvider.new +cfg.context_event_handler = handler +cfg.context_event_logger = logger +cfg.variable_parser = MyParser.new +cfg.audience_deserializer = MyAudienceDeserializer.new +cfg.scheduler = MyExecutor.new +sdk = ABSmartly.create(cfg) + +context_config = Absmartly.create_context_config +context_config.set_unit("session_id", "bf06d8cb5d8137290c4abb64155584fbdb64d8") +context_config.set_units(user_id: "123456") +context = sdk.create_context(context_config) +check.("ready", context.ready?) +treatment = context.treatment("exp_test_experiment") +check.("treatment Integer", treatment.is_a?(Integer)) +check.("variable_value", %w[red blue].include?(context.variable_value("button.color", "blue"))) +check.("peek_treatment", context.peek_treatment("exp_test_experiment") == treatment) +check.("variable_keys shape", context.variable_keys == { "button.color": "exp_test_experiment" }) +context.set_override("exp_test_experiment", 1) +context.set_overrides("exp_test_experiment" => 1, "exp_another_experiment" => 0) +context.set_attribute("session_id", "x") +context.set_attributes("customer_age" => "new_customer") +context.set_custom_assignment("experiment_name", 1) +context.set_custom_assignments("experiment_name" => 1, "another_experiment_name" => 0) +context.track("payment", { item_count: 1, total_amount: 1999.99 }) +context.publish +r = context.refresh +check.("refresh returns logger result", r == logger.events) +close_result = context.close +check.("close returns logger result", close_result == logger.events) +check.("closed?", context.closed?) +begin + context.treatment("exp_test_experiment"); check.("closed raises", false) +rescue IllegalStateException => e + check.("closed raises IllegalStateException text", e.message == "ABSmartly Context is closed") +end +begin + context.set_override("exp", 1); check.("set_override after close raises", false) +rescue IllegalStateException + check.("set_override after close raises", true) +end +begin + context.experiments; check.("experiments after close raises", false) +rescue IllegalStateException + check.("experiments after close raises", true) +end +check.("events", logger.events.include?("close") && logger.events.include?("publish")) + +# Rejected final publish on close: logged and sealed, no raise (1.3.0). +class RejectingHandler < ContextEventHandler + def publish(context, event); Exception.new("rejected"); end +end +cfg.context_event_handler = RejectingHandler.new +ctx2 = ABSmartly.create(cfg).create_context(context_config) +ctx2.treatment("exp_test_experiment") +begin + ctx2.close + check.("close on rejected publish does not raise and seals", ctx2.closed? && ctx2.pending_count == 0) +rescue Exception => e + 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) + +results.each { |n, s| puts "#{s} #{n}" } +exit(results.all? { |_, s| s == "ok" } ? 0 : 1) diff --git a/spec/compat_v1_3_0_spec.rb b/spec/compat_v1_3_0_spec.rb new file mode 100644 index 00000000..e2a8fad0 --- /dev/null +++ b/spec/compat_v1_3_0_spec.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +require "open3" +require "rbconfig" + +RSpec.describe "1.3.0 consumer compatibility" do + it "runs a customer app written against the 1.3.0 README with only require \"absmartly\"" do + lib = File.expand_path("../lib", __dir__) + script = File.expand_path("compat/v1_3_0_consumer.rb", __dir__) + out, err, status = Open3.capture3(RbConfig.ruby, "-W0", "-I", lib, script) + expect(out.lines.grep_v(/\Aok /)).to be_empty, out + err + expect(status.success?).to be(true), out + err + end +end diff --git a/spec/concurrency_spec.rb b/spec/concurrency_spec.rb index 787c08ad..cd0c4de8 100644 --- a/spec/concurrency_spec.rb +++ b/spec/concurrency_spec.rb @@ -36,7 +36,7 @@ let(:publish_future) { OpenStruct.new(success?: true) } let(:event_handler) do - ev = instance_double(ContextPublisher) + ev = instance_double(Absmartly::ContextPublisher) allow(ev).to receive(:publish).and_return(publish_future) ev end @@ -191,7 +191,7 @@ def create_context it "includes each queued event in at most one publish" do sent = [] sent_mutex = Mutex.new - handler = instance_double(ContextPublisher) + handler = instance_double(Absmartly::ContextPublisher) allow(handler).to receive(:publish) do |_ctx, event| sleep 0.02 sent_mutex.synchronize { sent.concat((event.goals || []).map(&:name)) } @@ -247,7 +247,7 @@ def handle_event(event, _data) it "does not strand events when a PUBLISH callback queues an event and closes" do sent = [] - handler = instance_double(ContextPublisher) + handler = instance_double(Absmartly::ContextPublisher) allow(handler).to receive(:publish) do |_ctx, event| sent.concat((event.goals || []).map(&:name)) publish_future diff --git a/spec/context_assignment_rules_spec.rb b/spec/context_assignment_rules_spec.rb index 11996712..d50b51ca 100644 --- a/spec/context_assignment_rules_spec.rb +++ b/spec/context_assignment_rules_spec.rb @@ -8,8 +8,22 @@ require "default_context_event_serializer" require "default_variable_parser" require "json/context_data" +require "timeout" RSpec.describe "Context assignment rules" do + # Reads retry when an assignment is evicted before its exposure claim; a + # regression that never stops retrying fails here instead of hanging CI. + # Threads an example started are killed afterwards, so a timed-out example + # can't leave one spinning and slow the rest of the suite. + around do |example| + before = Thread.list + begin + Timeout.timeout(10) { example.run } + ensure + (Thread.list - before).each(&:kill).each { |thread| thread.join(1) } + end + end + let(:clock) { Time.at(1620000000000 / 1000) } let(:session_id) { "e791e240fcd3df7d238cfc285f475e8152fcc0ec" } let(:variable_parser) { DefaultVariableParser.new } @@ -17,7 +31,7 @@ let(:publish_future) { OpenStruct.new(success?: true) } let(:published) { [] } let(:event_handler) do - handler = double("ContextPublisher") + handler = double("Absmartly::ContextPublisher") allow(handler).to receive(:publish) do |_ctx, event| published << event publish_future @@ -328,6 +342,490 @@ def published_exposures(context) expect(context.pending_count).to eq(1) end + def clocked_context(data, clock_object, units: {}, attributes: {}) + config = ContextConfig.create + config.set_units(units) + config.set_attributes(attributes) + Context.create(clock_object, config, OpenStruct.new(data_future: data, success?: true), data_provider, + event_handler, nil, variable_parser, audience_matcher, + application: "website", environment: "production") + end + + it "keeps the no-unit variant when the unit is set during that exposure's clock" do + holder = {} + sid = session_id + clock_object = Object.new + clock_object.define_singleton_method(:to_i) do + if holder[:arm] + holder[:arm] = false + holder[:context].set_unit("session_id", sid) + end + 123 + end + context = clocked_context(context_data([split_rule("0/100/0")]), clock_object, attributes: { country: "US" }) + holder[:context] = context + holder[:arm] = true + + expect(context.treatment("exp_test_abc")).to eq(0) + expect(context.treatment("exp_test_abc")).to eq(0) + expect(published_exposures(context).map { |e| [e.name, e.variant] }).to eq([["exp_test_abc", 0]]) + end + + it "rebuilds the no-unit variant if its exposure fails after the unit was set during the clock" do + holder = {} + sid = session_id + clock_object = Object.new + clock_object.define_singleton_method(:to_i) do + if holder[:arm] + holder[:arm] = false + holder[:context].set_unit("session_id", sid) + raise "clock failed" + end + 123 + end + context = clocked_context(context_data([split_rule("0/100/0")]), clock_object, attributes: { country: "US" }) + holder[:context] = context + holder[:arm] = true + + expect { context.treatment("exp_test_abc") }.to raise_error("clock failed") + expect(context.treatment("exp_test_abc")).to eq(1) + expect(published_exposures(context).map { |e| [e.name, e.variant] }).to eq([["exp_test_abc", 1]]) + end + + it "re-resolves a no-unit assignment evicted by set_unit between its lookup and exposure" do + context = create_context(context_data([split_rule("0/100/0")]), units: {}, attributes: { country: "US" }) + sid = session_id + armed = true + allow(context).to receive(:claim_and_queue_exposure).and_wrap_original do |original, assignment, *rest| + if armed + armed = false + context.set_unit("session_id", sid) + end + original.call(assignment, *rest) + end + + first = context.treatment("exp_test_abc") + expect(context.treatment("exp_test_abc")).to eq(first) + expect(published_exposures(context).map { |e| [e.name, e.variant] }).to eq([["exp_test_abc", first]]) + end + + it "re-resolves a variable read whose assignment set_unit evicted before its exposure" do + context = create_context(context_data([split_rule("0/100/0")]), units: {}, attributes: { country: "US" }) + sid = session_id + armed = true + allow(context).to receive(:claim_and_queue_exposure).and_wrap_original do |original, assignment, *rest| + if armed + armed = false + context.set_unit("session_id", sid) + end + original.call(assignment, *rest) + end + + first = context.variable_value("button.color", "default") + expect(context.variable_value("button.color", "default")).to eq(first) + variants = published_exposures(context).map { |e| [e.name, e.variant] } + expect(variants.map(&:first)).to eq(["exp_test_abc"]) + end + + # The refresh and set_unit land right after the lookup returns, before + # the caller decides which assignment its exposure claim must match. + %i[treatment variable_value].each do |read| + it "re-resolves a #{read} when a refresh and set_unit land right after its lookup" do + data = context_data([split_rule("0/100/0")]) + allow(data_provider).to receive(:context_data).and_return(OpenStruct.new(data_future: data, success?: true)) + context = create_context(data, units: {}, attributes: { country: "US" }) + sid = session_id + armed = true + allow(context).to receive(:assignment).and_wrap_original do |original, *args| + result = original.call(*args) + if armed + armed = false + context.refresh + context.set_unit("session_id", sid) + end + result + end + call = read == :treatment ? -> { context.treatment("exp_test_abc") } : -> { context.variable_value("button.color", "d") } + + first = call.call + expect(call.call).to eq(first) + expect(published_exposures(context).map(&:name)).to eq(["exp_test_abc"]) + end + end + + it "does not claim an exposure that set_unit is evicting" do + context = create_context(context_data([split_rule("0/100/0")]), units: {}, attributes: { country: "US" }) + sid = session_id + assignment = context.send(:assignment, "exp_test_abc") + cache = context.instance_variable_get(:@assignment_cache) + in_eviction = Queue.new + resume = Queue.new + # Park set_unit inside its eviction, holding the assignment lock, after + # it has read which exposures are in progress. + allow(cache).to receive(:delete_if).and_wrap_original do |original, &block| + if Thread.current[:gate] + Thread.current[:gate] = false + in_eviction << true + resume.pop + end + original.call(&block) + end + setter = Thread.new do + Thread.current[:gate] = true + context.set_unit("session_id", sid) + end + reader = nil + begin + Timeout.timeout(5) { in_eviction.pop } + reader = Thread.new { context.send(:claim_and_queue_exposure, assignment, "exp_test_abc") } + expect(reader.join(0.2)).to be_nil + resume << true + Timeout.timeout(5) { setter.join } + expect(Timeout.timeout(5) { reader.value }).to eq(:evicted) + ensure + resume << true + setter.join(1) || setter.kill + reader&.join(1) || reader&.kill + end + + expect(context.treatment("exp_test_abc")).to eq(1) + expect(published_exposures(context).map { |e| [e.name, e.variant] }).to eq([["exp_test_abc", 1]]) + end + + it "lets a timeout interrupt an exposure's cleanup waiting for the assignment lock" do + holder = {} + sid = session_id + in_clock = Queue.new + clock_object = Object.new + clock_object.define_singleton_method(:to_i) do + if holder[:arm] + holder[:arm] = false + holder[:context].set_unit("session_id", sid) + in_clock << true + sleep + end + 123 + end + context = clocked_context(context_data([split_rule("0/100/0")]), clock_object, attributes: { country: "US" }) + holder[:context] = context + lock = context.instance_variable_get(:@assignment_mutex) + locked = Queue.new + release = Queue.new + reader = Thread.new do + holder[:arm] = true + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + begin + Timeout.timeout(0.3) { context.treatment("exp_test_abc") } + rescue Timeout::Error + nil + end + Process.clock_gettime(Process::CLOCK_MONOTONIC) - started + end + locker = nil + begin + Timeout.timeout(5) { in_clock.pop } + # Held when the timeout unwinds the clock, so cleanup must wait for it. + locker = Thread.new { lock.synchronize { locked << true; Timeout.timeout(1.5) { release.pop } rescue nil } } + Timeout.timeout(5) { locked.pop } + expect(Timeout.timeout(5) { reader.value }).to be < 1 + ensure + release << true + locker&.join(1) || locker&.kill + reader.join(1) || reader.kill + end + expect(context.treatment("exp_test_abc")).to eq(1) + expect(context.instance_variable_get(:@exposing)).to be_empty + end + + def unit_setting_clock(holder, sid, raise_after: false) + clock_object = Object.new + clock_object.define_singleton_method(:to_i) do + if Thread.current[:arm] + Thread.current[:arm] = false + holder[:context].set_unit("session_id", sid) + holder[:in_clock] << true + holder[:resume].pop + raise "clock failed" if raise_after + end + 123 + end + clock_object + end + + %i[treatment variable_value].each do |read| + it "a #{read} waiting on a failed no-unit exposure resolves the unit set during it" do + holder = { in_clock: Queue.new, resume: Queue.new } + clock_object = unit_setting_clock(holder, session_id, raise_after: true) + context = clocked_context(context_data([split_rule("0/100/0")]), clock_object, attributes: { country: "US" }) + holder[:context] = context + call = read == :treatment ? -> { context.treatment("exp_test_abc") } : -> { context.variable_value("button.color", "d") } + owner = Thread.new do + Thread.current[:arm] = true + call.call + rescue RuntimeError + nil + end + waiter = nil + begin + Timeout.timeout(5) { holder[:in_clock].pop } + waiter = Thread.new { call.call } + expect(waiter.join(0.1)).to be_nil + holder[:resume] << true + Timeout.timeout(5) { owner.join } + expected = read == :treatment ? 1 : "blue" + expect(Timeout.timeout(5) { waiter.value }).to eq(expected) + ensure + holder[:resume] << true + owner.join(1) || owner.kill + waiter&.join(1) || waiter&.kill + end + expect(published_exposures(context).map { |e| [e.name, e.variant] }).to eq([["exp_test_abc", 1]]) + end + end + + it "a concurrent read during a no-unit exposure that sets the unit serves the variant being exposed" do + holder = { in_clock: Queue.new, resume: Queue.new } + clock_object = unit_setting_clock(holder, session_id) + context = clocked_context(context_data([split_rule("0/100/0")]), clock_object, attributes: { country: "US" }) + holder[:context] = context + owner = Thread.new do + Thread.current[:arm] = true + context.treatment("exp_test_abc") + end + begin + Timeout.timeout(5) { holder[:in_clock].pop } + expect(context.peek_treatment("exp_test_abc")).to eq(0) + holder[:resume] << true + expect(Timeout.timeout(5) { owner.value }).to eq(0) + ensure + holder[:resume] << true + owner.join(1) || owner.kill + end + expect(context.treatment("exp_test_abc")).to eq(0) + expect(published_exposures(context).map { |e| [e.name, e.variant] }).to eq([["exp_test_abc", 0]]) + end + + it "reuses a no-unit split assignment while its unit is still missing" do + context = create_context(context_data([split_rule("0/100/0")]), units: {}, attributes: { country: "US" }) + context.peek_treatment("exp_test_abc") + matcher = context.send(:rule_matcher) + allow(matcher).to receive(:evaluate_parsed_rules).and_call_original + 3.times { context.peek_treatment("exp_test_abc") } + expect(matcher).not_to have_received(:evaluate_parsed_rules) + end + + # Another read rebuilds the cached entry right after this read's lookup; + # the exposure claim must then resolve again rather than expose the old one. + %i[treatment variable_value].each do |read| + it "re-resolves a #{read} whose cached assignment another read rebuilt after its lookup" do + context = create_context(context_data([assign_rule(1)]), attributes: { country: "US" }) + armed = true + allow(context).to receive(:assignment).and_wrap_original do |original, *args| + result = original.call(*args) + if armed + armed = false + context.set_override("exp_test_abc", 0) + context.peek_treatment("exp_test_abc") + end + result + end + call = read == :treatment ? -> { context.treatment("exp_test_abc") } : -> { context.variable_value("button.color", "d") } + expected = read == :treatment ? 0 : "d" + + expect(call.call).to eq(expected) + expect(call.call).to eq(expected) + expect(published_exposures(context).map { |e| [e.name, e.variant] }).to eq([["exp_test_abc", 0]]) + end + end + + it "takes no exposure claim or stale check on a warm read of an exposed experiment" do + context = create_context(context_data([assign_rule(1)]), attributes: { country: "US" }) + context.treatment("exp_test_abc") + context.variable_value("button.color", "d") + allow(context).to receive(:claim_and_queue_exposure).and_call_original + allow(context).to receive(:stale_missing_unit?).and_call_original + + context.variable_value("button.color", "d") + context.peek_treatment("exp_test_abc") + + expect(context).not_to have_received(:claim_and_queue_exposure) + expect(context).not_to have_received(:stale_missing_unit?) + end + + it "keeps the no-unit variant when its clock sets the unit and an attribute, then reads" do + holder = {} + sid = session_id + clock_object = Object.new + clock_object.define_singleton_method(:to_i) do + if holder[:arm] + holder[:arm] = false + holder[:context].set_unit("session_id", sid) + holder[:context].set_attribute("age", 30) + holder[:peeked] = holder[:context].peek_treatment("exp_test_abc") + end + 123 + end + context = clocked_context(context_data([split_rule("0/100/0")]), clock_object, attributes: { country: "US" }) + holder[:context] = context + holder[:arm] = true + + expect(context.treatment("exp_test_abc")).to eq(0) + expect(holder[:peeked]).to eq(0) + expect(context.treatment("exp_test_abc")).to eq(0) + expect(published_exposures(context).map { |e| [e.name, e.variant] }).to eq([["exp_test_abc", 0]]) + end + + # The first exposure's logger sets an override and returns a value that + # looks like a claim status; neither changes what that read served. + [ + ["serves and exposes the same", ->(context) { context.variable_value("button.color", "default") }, "red"], + ["a first treatment serves and exposes the same", ->(context) { context.treatment("exp_test_abc") }, 2] + ].each do |label, first_read, served| + %i[evicted logged].each do |returned| + it "#{label} when the exposure logger returns #{returned.inspect}" do + holder = { calls: 0 } + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + next unless event == ContextEventLogger::EVENT_TYPE::EXPOSURE + + holder[:calls] += 1 + next unless holder[:calls] == 1 + + holder[:context].set_override("exp_test_abc", 0) + returned + end + end.new + config = ContextConfig.create + config.set_units(session_id: session_id) + config.set_attributes(country: "US") + context = Context.create(clock, config, OpenStruct.new(data_future: context_data(nil), success?: true), + data_provider, event_handler, logger, variable_parser, audience_matcher, + application: "website", environment: "production") + holder[:context] = context + + expect(first_read.call(context)).to eq(served) + expect(context.treatment("exp_test_abc")).to eq(0) + expect(published_exposures(context).map { |e| [e.name, e.variant] }) + .to eq([["exp_test_abc", 2], ["exp_test_abc", 0]]) + end + end + end + + it "the public queue_exposure queues any assignment it is given, as in 1.3.0" do + context = create_context(context_data([split_rule("0/100/0")]), units: {}, attributes: { country: "US" }) + no_unit = context.send(:assignment, "exp_test_abc") + context.set_unit("session_id", session_id) + + context.queue_exposure(no_unit) + expect(context.pending_count).to eq(1) + expect(published_exposures(context).map { |e| [e.name, e.variant] }).to eq([["exp_test_abc", 0]]) + end + + [[false, 1], [true, 1], [true, 2]].each do |with_attribute, gate_at| + it "keeps the no-unit variant when a read overlaps its exposure completing#{" after an attribute update" if with_attribute} at check #{gate_at}" do + holder = { in_clock: Queue.new, resume: Queue.new } + sid = session_id + clock_object = Object.new + clock_object.define_singleton_method(:to_i) do + if Thread.current[:arm] + Thread.current[:arm] = false + holder[:context].set_unit("session_id", sid) + holder[:context].set_attribute("age", 30) if with_attribute + holder[:in_clock] << true + holder[:resume].pop + end + 123 + end + context = clocked_context(context_data([split_rule("0/100/0")]), clock_object, attributes: { country: "US" }) + holder[:context] = context + queue_mutex = context.instance_variable_get(:@queue_mutex) + checking = Queue.new + proceed = Queue.new + # Park the reader as it takes the queue lock to check the assignment's + # exposure state, until the owner has completed its exposure. + allow(queue_mutex).to receive(:synchronize).and_wrap_original do |original, &block| + if Thread.current[:gate] + Thread.current[:checks] = (Thread.current[:checks] || 0) + 1 + if Thread.current[:checks] == gate_at + Thread.current[:gate] = false + checking << true + proceed.pop + end + end + original.call(&block) + end + owner = Thread.new do + Thread.current[:arm] = true + context.treatment("exp_test_abc") + end + reader = nil + begin + Timeout.timeout(5) { holder[:in_clock].pop } + reader = Thread.new do + Thread.current[:gate] = true + context.peek_treatment("exp_test_abc") + end + Timeout.timeout(5) { checking.pop } + holder[:resume] << true + expect(Timeout.timeout(5) { owner.value }).to eq(0) + proceed << true + expect(Timeout.timeout(5) { reader.value }).to eq(0) + ensure + holder[:resume] << true + proceed << true + owner.join(1) || owner.kill + reader&.join(1) || reader&.kill + end + expect(context.treatment("exp_test_abc")).to eq(0) + expect(published_exposures(context).map { |e| [e.name, e.variant] }).to eq([["exp_test_abc", 0]]) + end + end + + it "does not take the queue lock to check a no-unit assignment already exposed" do + context = create_context(context_data([split_rule("0/100/0")]), units: {}, attributes: { country: "US" }) + context.treatment("exp_test_abc") + context.set_unit("session_id", session_id) + context.set_attribute("age", 30) + assignment = context.send(:assignment, "exp_test_abc") + mutex = context.instance_variable_get(:@queue_mutex) + expect(mutex).not_to receive(:synchronize) + expect(context.send(:exposed_or_exposing?, assignment)).to be true + end + + it "does not reinstall an old variable assignment after refresh exposes the new one" do + old_data = context_data([assign_rule(2)]) + new_data = context_data([assign_rule(1)]) + allow(data_provider).to receive(:context_data).and_return(OpenStruct.new(data_future: new_data, success?: true)) + context = create_context(old_data, attributes: { country: "US" }) + armed = true + allow(context).to receive(:assignment).and_wrap_original do |original, *args| + result = original.call(*args) + if armed + armed = false + context.refresh + expect(context.variable_value("button.color", "d")).to eq("blue") + end + result + end + context.variable_value("button.color", "d") + expect(context.variable_value("button.color", "d")).to eq("blue") + variants = published_exposures(context).select { |e| e.name == "exp_test_abc" }.map(&:variant) + expect(variants.count(1)).to eq(1) + end + + it "uses the latest String or Symbol spelling of an attribute in the built-in evaluator" do + staging = { and: [{ eq: [{ var: "environment" }, { value: "staging" }] }] } + context = create_context(context_data([assign_rule(1, conditions: staging)])) + context.set_attribute("environment", "prod") + expect(context.treatment("exp_test_abc")).to eq(2) + + context.set_attribute(:environment, "staging") + expect(context.treatment("exp_test_abc")).to eq(1) + + context.set_attribute("environment", "prod") + expect(context.treatment("exp_test_abc")).to eq(2) + end + it "keeps an assign rule assignment when the unit is set" do context = create_context(context_data([assign_rule(1)]), units: {}, attributes: { country: "US" }) expect(context.treatment("exp_test_abc")).to eq(1) @@ -388,9 +886,64 @@ def create_with(matcher, data, attributes: {}) expect(context.treatment("exp_test_abc")).to eq(1) expect(published_exposures(context).first.rule_override).to eq(true) end + + it "passes the caller's attribute keys to the custom matcher when rules use the default engine" do + seen = [] + matcher = LegacyAudienceMatcher.new + matcher.define_singleton_method(:evaluate) do |audience, attributes| + seen << attributes.keys + super(audience, attributes) + end + audience = JSON.generate(filter: [{ eq: [{ var: "country" }, { value: "US" }] }]) + data = context_data([assign_rule(1)], audience: audience, audienceStrict: true) + context = create_with(matcher, data, attributes: { country: "GB" }) + + expect(context.treatment("exp_test_abc")).to eq(0) + context.set_attribute(:age, 30) + expect(context.treatment("exp_test_abc")).to eq(0) + expect(seen.map { |keys| keys.grep(Symbol) }).to eq([[:country], [:country, :age]]) + end end describe "cached reads" do + it "builds one attribute map for the rules and the audience of each resolution and revalidation" do + audience = JSON.generate(filter: [{ eq: [{ var: "country" }, { value: "US" }] }]) + context = create_context(context_data([assign_rule(1)], audience: audience), attributes: { country: "GB" }) + builds = 0 + allow(context).to receive(:evaluator_attributes).and_wrap_original do |original| + builds += 1 + original.call + end + audience_inputs = [] + allow(audience_matcher).to receive(:evaluate).and_wrap_original do |original, filter, attributes| + audience_inputs << attributes + original.call(filter, attributes) + end + + expect(context.treatment("exp_test_abc")).to eq(2) + expect(builds).to eq(1) + context.set_attribute("age", 30) + expect(context.treatment("exp_test_abc")).to eq(2) + expect(builds).to eq(2) + expect(audience_inputs.map { |attributes| attributes["age"] }).to eq([nil, 30]) + end + + it "parses rules once at install, not on resolution or attribute revalidation" do + parses = 0 + allow(audience_matcher).to receive(:parse_rules).and_wrap_original do |original, *args| + parses += 1 + original.call(*args) + end + context = create_context(context_data([assign_rule(1)]), attributes: { country: "US" }) + expect(parses).to eq(1) + expect(context.treatment("exp_test_abc")).to eq(1) + 3.times do |i| + context.set_attribute("unrelated", i) + expect(context.peek_treatment("exp_test_abc")).to eq(1) + end + expect(parses).to eq(1) + end + def count_rule_evaluations calls = 0 allow(audience_matcher).to receive(:evaluate_parsed_rules).and_wrap_original do |original, *args| diff --git a/spec/context_holdouts_spec.rb b/spec/context_holdouts_spec.rb index 2e9e670d..9afbe0c8 100644 --- a/spec/context_holdouts_spec.rb +++ b/spec/context_holdouts_spec.rb @@ -881,13 +881,14 @@ def three_arm_context(seeds) end # variable_value walks the key's candidates from the state it started - # with; a logger callback on the first candidate's exposure refreshes - # and exposes the second one under the new data before the walk reaches - # it, the interleaving of a read overlapping a refresh. + # with. exp_a fails its strict audience, so it loses but the walk still + # exposes its holdout_g; a logger callback on that exposure refreshes + # and exposes exp_b under the new data before the walk reaches it, the + # interleaving of a read overlapping a refresh. def overlapping_read(context, steps) fired = false allow(event_logger).to receive(:handle_event) do |_type, data| - next if fired || !(data.is_a?(Exposure) && data.id == 1) + next if fired || !(data.is_a?(Exposure) && data.id == 12) fired = true steps.call @@ -895,52 +896,57 @@ def overlapping_read(context, steps) context.variable_value("color", "default") end - def shared_key_experiments - first = experiment(1, "exp_a") - first[:variants] = [{ name: "A", config: '{"color":"a_control"}' }, { name: "B", config: '{"other":"x"}' }] - [first, with_variables(experiment(2, "exp_b", holdout_ids: [11]), "color")] + def shared_key_experiments(covered: true) + first = with_variables(experiment(1, "exp_a", holdout_ids: [12], audienceStrict: true, + audience: '{"filter":[{"gte":[{"var":"age"},{"value":20}]}]}'), + "color") + second = with_variables(experiment(2, "exp_b", holdout_ids: covered ? [11] : nil), "color") + [first, second] + end + + def shared_key_holdouts(seeds, iteration: 1) + [holdout(11, "holdout_h", seeds, iteration: iteration), holdout(12, "holdout_g", HOLDOUT_B)] end it "does not let a read that started before a refresh expose the new arm again" do - context = create_context(data_of(shared_key_experiments, [holdout(11, "holdout_h", HOLDOUT_B)])) + context = create_context(data_of(shared_key_experiments, shared_key_holdouts(HOLDOUT_B))) result = overlapping_read(context, lambda { - refresh(context, data_of(shared_key_experiments, [holdout(11, "holdout_h", HOLDOUT_A, iteration: 2)])) + refresh(context, data_of(shared_key_experiments, shared_key_holdouts(HOLDOUT_A, iteration: 2))) expect(context.treatment("exp_b")).to eq(0) }) context.treatment("exp_b") expect(result).to eq("control") - expect(exposures_of(context)).to eq([own_exposure(1, "exp_a", NORMAL_VARIANT), holdout_exposure(11, "holdout_h", 0)]) + expect(exposures_of(context)).to eq([holdout_exposure(12, "holdout_g", 1), holdout_exposure(11, "holdout_h", 0)]) end it "does not expose an experiment again when a read meets a non-suppressing new arm" do - context = create_context(data_of(shared_key_experiments, [holdout(11, "holdout_h", HOLDOUT_A)])) + context = create_context(data_of(shared_key_experiments, shared_key_holdouts(HOLDOUT_A))) result = overlapping_read(context, lambda { - refresh(context, data_of(shared_key_experiments, [holdout(11, "holdout_h", HOLDOUT_B, iteration: 2)])) + refresh(context, data_of(shared_key_experiments, shared_key_holdouts(HOLDOUT_B, iteration: 2))) expect(context.treatment("exp_b")).to eq(NORMAL_VARIANT) }) context.treatment("exp_b") expect(result).to eq("treatment") - expect(exposures_of(context)).to eq([own_exposure(1, "exp_a", NORMAL_VARIANT), + expect(exposures_of(context)).to eq([holdout_exposure(12, "holdout_g", 1), own_exposure(2, "exp_b", NORMAL_VARIANT), holdout_exposure(11, "holdout_h", 1)]) end it "does not expose an old arm again when a read resumes after the holdout is removed" do - context = create_context(data_of(shared_key_experiments, [holdout(11, "holdout_h", HOLDOUT_A)])) + context = create_context(data_of(shared_key_experiments, shared_key_holdouts(HOLDOUT_A))) expect(context.treatment("exp_b")).to eq(0) - uncovered = shared_key_experiments.tap { |e| e[1].delete(:holdoutIds) } result = overlapping_read(context, lambda { - refresh(context, data_of(shared_key_experiments, [holdout(11, "holdout_h", HOLDOUT_B, iteration: 2)])) + refresh(context, data_of(shared_key_experiments, shared_key_holdouts(HOLDOUT_B, iteration: 2))) expect(context.treatment("exp_b")).to eq(NORMAL_VARIANT) - refresh(context, data_of(uncovered, [])) + refresh(context, data_of(shared_key_experiments(covered: false), shared_key_holdouts(HOLDOUT_B, iteration: 2))) }) context.treatment("exp_b") expect(result).to eq("treatment") # Removing the coverage re-resolves exp_b once (scenario 225); the # iteration 1 arm is never exposed again. - expect(exposures_of(context)).to eq([holdout_exposure(11, "holdout_h", 0), own_exposure(1, "exp_a", NORMAL_VARIANT), + expect(exposures_of(context)).to eq([holdout_exposure(11, "holdout_h", 0), holdout_exposure(12, "holdout_g", 1), own_exposure(2, "exp_b", NORMAL_VARIANT), holdout_exposure(11, "holdout_h", 1), own_exposure(2, "exp_b", NORMAL_VARIANT)]) end @@ -1032,6 +1038,100 @@ def shared_key_experiments holdout_exposure(11, "holdout_user_id", 1, unit: "user_id")]) end + it "keeps the no-unit holdout result when the unit is set during that exposure's clock" do + holder = {} + clock_object = Object.new + clock_object.define_singleton_method(:to_i) do + if holder[:arm] + holder[:arm] = false + holder[:context].set_unit("user_id", UID) + end + 1_620_000_000 + end + config = ContextConfig.create + data = data_of([experiment(1, "exp_mid", unit_type: "user_id", full_on_variant: 2, holdout_ids: [11])], + [holdout(11, "holdout_user_id", HOLDOUT_B, unit_type: "user_id")]) + context = Context.create(clock_object, config, OpenStruct.new(data_future: data, success?: true), data_provider, + event_handler, event_logger, variable_parser, audience_matcher) + holder[:context] = context + holder[:arm] = true + + expect(context.treatment("exp_mid")).to eq(2) + expect(context.treatment("exp_mid")).to eq(2) + expect(context.pending_count).to eq(1) + end + + it "a direct queue_exposure of a held-out assignment queues only its holdout exposure" do + context = create_context(data_of([experiment(1, "exp_direct", holdout_ids: [10])], + [holdout(10, "holdout_a", HOLDOUT_A)])) + assignment = context.send(:assignment, "exp_direct") + expect(assignment.suppressed).to be true + + context.queue_exposure(assignment) + expect(context.queue_exposure(assignment)).to be_nil + expect(exposures_of(context).map { |e| e[1] }).to eq(["holdout_a"]) + end + + it "rebuilds a held-out no-unit result whose exposure failed after its clock set the unit" do + holder = {} + clock_object = Object.new + clock_object.define_singleton_method(:to_i) do + if holder[:arm] + holder[:arm] = false + holder[:context].set_unit("user_id", UID) + raise "clock failed" + end + 1_620_000_000 + end + config = ContextConfig.create + data = data_of([experiment(1, "exp_fail", unit_type: "user_id", holdout_ids: [11])], + [holdout(11, "holdout_user_id", HOLDOUT_A, unit_type: "user_id")]) + context = Context.create(clock_object, config, OpenStruct.new(data_future: data, success?: true), data_provider, + event_handler, event_logger, variable_parser, audience_matcher) + holder[:context] = context + holder[:arm] = true + + expect { Timeout.timeout(5) { context.treatment("exp_fail") } }.to raise_error("clock failed") + expect(Timeout.timeout(5) { context.treatment("exp_fail") }).to eq(0) + expect(exposures_of(context).map { |e| e[1] }).to eq(["holdout_user_id"]) + end + + it "stamps an experiment and its holdout exposures with one clock read" do + reads = [] + holder = {} + clock_object = Object.new + clock_object.define_singleton_method(:to_i) do + holder[:context]&.set_unit("user_id", UID) unless holder[:context]&.get_unit("user_id") + reads << (1_620_000_000 + reads.size) + reads.last + end + config = ContextConfig.create + config.set_unit(UNIT_TYPE, UID_NOT_HELD_OUT) + data = data_of([experiment(2, "exp_two", holdout_ids: [11])], + [holdout(11, "h11", HOLDOUT_A)]) + context = Context.create(clock_object, config, OpenStruct.new(data_future: data, success?: true), data_provider, + event_handler, event_logger, variable_parser, audience_matcher) + holder[:context] = context + reads.clear + + Timeout.timeout(5) { context.treatment("exp_two") } + context.publish + sent = published.flat_map { |event| event.exposures || [] } + expect(sent.map(&:name)).to eq(%w[exp_two h11]) + expect(sent.map(&:exposed_at).uniq.size).to eq(1) + end + + it "skips the stale no-unit check on warm reads of an exposed holdout-covered experiment" do + context = create_context(data_of([experiment(2, "exp_warm", holdout_ids: [11])], [holdout(11, "h11", HOLDOUT_A)])) + context.treatment("exp_warm") + allow(context).to receive(:stale_missing_unit?).and_call_original + 5.times do + context.treatment("exp_warm") + context.peek_treatment("exp_warm") + end + expect(context).not_to have_received(:stale_missing_unit?) + end + it "keeps an exposed assignment so the experiment is not exposed twice" do context = create_context(data_of([experiment(1, "exp_exposed", unit_type: "user_id", full_on_variant: 2, holdout_ids: [11])], @@ -1072,6 +1172,9 @@ def shared_key_experiments expect(context.pending_count).to eq(2) context.set_unit("user_id", UID) + cache = context.instance_variable_get(:@assignment_cache) + expect(cache).not_to have_key("exp_late") + expect(cache).to have_key("exp_present") expect(context.treatment("exp_late")).to eq(2) expect(context.pending_count).to eq(4) @@ -1194,6 +1297,108 @@ def shared_key_experiments holdout_exposure(11, "holdout_override_late", 1, unit: "user_id")]) end + # As java-sdk: an override has no pinned holdout arms; each non-peek + # variable read resolves them live, so the first one after set_unit + # exposes the holdout. treatment does not, once the override is exposed. + it "exposes an exposed override's holdout on the next variable read after its unit arrives" do + exp = with_variables(experiment(1, "exp_override_var", unit_type: "user_id", holdout_ids: [11]), "my_var") + context = create_context(data_of([exp], [holdout(11, "holdout_override_var", HOLDOUT_B, unit_type: "user_id")]), + units: { UNIT_TYPE => UID }, overrides: { "exp_override_var" => 1 }) + + # Read twice while the unit is unset: the exposed override's missing + # arm must not mark its holdouts done. + 2.times { expect(context.variable_value("my_var", "default")).to eq("treatment") } + own = own_exposure(1, "exp_override_var", 1, unit: "user_id", assigned: false, overridden: true) + expect(exposures_of(context)).to eq([own]) + + context.set_unit("user_id", UID) + expect(context.treatment("exp_override_var")).to eq(1) + expect(context.peek_variable_value("my_var", "default")).to eq("treatment") + expect(context.pending_count).to eq(0) + + 2.times { expect(context.variable_value("my_var", "default")).to eq("treatment") } + expect(exposures_of(context)).to eq([own, holdout_exposure(11, "holdout_override_var", 1, unit: "user_id")]) + end + + it "stops entering the holdout path once an exposed override's holdouts are all exposed" do + exp = with_variables(experiment(1, "exp_override_warm", unit_type: "user_id", holdout_ids: [11]), "my_var") + context = create_context(data_of([exp], [holdout(11, "holdout_override_warm", HOLDOUT_B, unit_type: "user_id")]), + units: {}, overrides: { "exp_override_warm" => 1 }) + context.variable_value("my_var", "default") + context.set_unit("user_id", UID) + context.variable_value("my_var", "default") + context.variable_value("my_var", "default") + + expect(context).not_to receive(:queue_holdout_exposures) + 3.times { expect(context.variable_value("my_var", "default")).to eq("treatment") } + expect(exposures_of(context).size).to eq(2) + end + + it "does not resolve an override's missing holdout arms while its unit is still unset" do + exp = with_variables(experiment(1, "exp_override_nounit", unit_type: "user_id", holdout_ids: [11]), "my_var") + context = create_context(data_of([exp], [holdout(11, "holdout_override_nounit", HOLDOUT_B, unit_type: "user_id")]), + units: {}, overrides: { "exp_override_nounit" => 1 }) + context.variable_value("my_var", "default") + + arms = context.instance_variable_get(:@assignment_cache)["exp_override_nounit"].holdout_assignments + expect(context).not_to receive(:holdout_assignment) + 3.times { expect(context.variable_value("my_var", "default")).to eq("treatment") } + expect(context.instance_variable_get(:@assignment_cache)["exp_override_nounit"].holdout_assignments).to equal(arms) + end + + # Only an override's arms are resolved late, as java-sdk only resolves + # holdouts live for an override: an exposed assignment that was not + # overridden keeps the no-unit decision it was exposed with. + it "does not expose the holdout of an exposed, not overridden experiment after its unit arrives" do + exp = with_variables(experiment(1, "exp_plain_late", unit_type: "user_id", holdout_ids: [11]), "my_var") + context = create_context(data_of([exp], [holdout(11, "holdout_plain_late", HOLDOUT_B, unit_type: "user_id")]), + units: { UNIT_TYPE => UID }) + + # treatment exposes the no-unit assignment (variant 0, not assigned); + # set_unit then keeps it, and later variable reads find it exposed. + expect(context.treatment("exp_plain_late")).to eq(0) + context.set_unit("user_id", UID) + 2.times { expect(context.variable_value("my_var", "default")).to eq("default") } + + expect(exposures_of(context)).to eq([own_exposure(1, "exp_plain_late", 0, unit: "user_id", assigned: false)]) + end + + # A refresh with the same holdout iteration keeps the override cached; + # its late arm is decided after it, so it uses the live seeds and name. + [["renamed", { name: "holdout_renamed" }, "holdout_renamed", 1], + ["reseeded", { seedHi: HOLDOUT_A[0], seedLo: HOLDOUT_A[1] }, "holdout_override_live", 0]].each do |label, edit, name, arm| + it "decides an override's late holdout arm from the #{label} live holdout, as java-sdk" do + exp = with_variables(experiment(1, "exp_override_live", unit_type: "user_id", holdout_ids: [11]), "my_var") + original = holdout(11, "holdout_override_live", HOLDOUT_B, unit_type: "user_id") + context = create_context(data_of([exp], [original]), units: {}, overrides: { "exp_override_live" => 1 }) + + expect(context.variable_value("my_var", "default")).to eq("treatment") + refresh(context, data_of([exp], [original.merge(edit)])) + context.set_unit("user_id", UID) + expect(context.variable_value("my_var", "default")).to eq("treatment") + + expect(exposures_of(context)).to eq([own_exposure(1, "exp_override_live", 1, unit: "user_id", assigned: false, + overridden: true), + holdout_exposure(11, name, arm, unit: "user_id")]) + end + end + + it "exposes a treatment-exposed override's holdout on the next variable read after its unit arrives" do + exp = with_variables(experiment(1, "exp_override_tr", unit_type: "user_id", holdout_ids: [11, 12]), "my_var") + context = create_context(data_of([exp], [holdout(11, "holdout_a", HOLDOUT_A, unit_type: "user_id"), + holdout(12, "holdout_b", HOLDOUT_B, unit_type: "user_id")]), + units: {}, overrides: { "exp_override_tr" => 1 }) + + expect(context.treatment("exp_override_tr")).to eq(1) + context.set_unit("user_id", UID) + expect(context.variable_value("my_var", "default")).to eq("treatment") + + expect(exposures_of(context)).to eq([own_exposure(1, "exp_override_tr", 1, unit: "user_id", assigned: false, + overridden: true), + holdout_exposure(11, "holdout_a", 0, unit: "user_id"), + holdout_exposure(12, "holdout_b", 1, unit: "user_id")]) + end + it "applies a custom assignment once the unit arrives" do context = create_context(data_of([experiment(1, "exp_custom_late", unit_type: "user_id", holdout_ids: [11])], [holdout(11, "holdout_custom_late", HOLDOUT_B, unit_type: "user_id")]), @@ -1282,24 +1487,24 @@ def verdict(uid, seeds, split) expect(exposures_of(context)).to eq([holdout_exposure(11, "holdout_a", 0)]) end - it "skips an overridden held-out experiment when picking the control fallback" do + it "lets an overridden held-out experiment win, giving the default when its variant lacks the key" do first = experiment(1, "exp_ov", holdout_ids: [11]) first[:variants] = [{ name: "A", config: '{"color":"ov_control"}' }, { name: "B", config: '{"other":"x"}' }] second = with_variables(experiment(2, "exp_second", holdout_ids: [11]), "color") context = create_context(data_of([first, second], [holdout(11, "holdout_a", HOLDOUT_A)]), overrides: { "exp_ov" => 1 }) - expect(context.peek_variable_value("color", "default")).to eq("control") + expect(context.peek_variable_value("color", "default")).to eq("default") end - it "skips a rule-won held-out experiment when picking the control fallback" do + it "lets a rule-won held-out experiment win, giving the default when its variant lacks the key" do first = experiment(1, "exp_rule", holdout_ids: [11], assignmentRules: US_RULE) first[:variants] = [{ name: "A", config: '{"color":"rule_control"}' }, { name: "B", config: '{"other":"x"}' }] second = with_variables(experiment(2, "exp_second", holdout_ids: [11]), "color") context = create_context(data_of([first, second], [holdout(11, "holdout_a", HOLDOUT_A)])) context.set_attribute("country", "US") - expect(context.peek_variable_value("color", "default")).to eq("control") + expect(context.peek_variable_value("color", "default")).to eq("default") end it "keeps the first suppressed experiment's control even when it lacks the key" do @@ -1317,8 +1522,9 @@ def verdict(uid, seeds, split) context.set_attribute("country", "US") expect(context.variable_value("color", "default")).to eq("treatment") - expect(exposures_of(context)).to eq([own_exposure(1, "exp_holdout_rules", 1, assigned: false, rule_override: true), - holdout_exposure(11, "holdout_rules_suppression", 0)]) + # java-sdk variableValueOnHeldOutRuleWonExperiment: the holdout first. + expect(exposures_of(context)).to eq([holdout_exposure(11, "holdout_rules_suppression", 0), + own_exposure(1, "exp_holdout_rules", 1, assigned: false, rule_override: true)]) end it "prefers a rule-won experiment over a suppressed one" do diff --git a/spec/context_shared_variable_keys_spec.rb b/spec/context_shared_variable_keys_spec.rb new file mode 100644 index 00000000..ce7388e8 --- /dev/null +++ b/spec/context_shared_variable_keys_spec.rb @@ -0,0 +1,752 @@ +# frozen_string_literal: true + +require "context" +require "context_config" +require "audience_matcher" +require "default_audience_deserializer" +require "default_context_data_deserializer" +require "default_variable_parser" +require "json/context_data" + +# A variable key defined by several experiments, as java-sdk +# Context.getVariableAssignment resolves it: the candidates are walked in +# experiment id order, the first one the unit is assigned, overridden or +# rule-assigned in wins, and only that one is exposed. A winner whose variant +# lacks the key gives the caller default; the walk never moves on to a later +# candidate because of the arm the unit got. +module ContextSharedVariableKeysSpec + RSpec.describe "Context shared variable keys" do + UNIT_TYPE = "session_id" + UID = "e791e240fcd3df7d238cfc285f475e8152fcc0ec" + # split [0.5, 0.5] with seeds 100/200 gives UID variant 1. + VARIANT = 1 + # split [0.1, 0.9] with seeds 13/111 holds UID out (arm 0); 1/222 does not (arm 1). + HOLDING_OUT = [13, 111].freeze + NOT_HOLDING_OUT = [1, 222].freeze + US_ONLY = '{"filter":[{"eq":[{"var":"country"},{"value":"US"}]}]}' + US_RULE = JSON.generate(rules: [{ name: "US", type: "assign", + conditions: { and: [{ eq: [{ var: "country" }, { value: "US" }] }] }, + environments: [], variant: 0 }]) + + let(:clock) { Time.at(1620000000000 / 1000) } + let(:published) { [] } + let(:event_handler) do + handler = double("ContextPublisher") + allow(handler).to receive(:publish) do |_ctx, event| + published << event + OpenStruct.new(success?: true) + end + handler + end + let(:event_logger) do + logger = double("ContextEventLogger") + allow(logger).to receive(:handle_event) + logger + end + + def experiment(id, name, configs: ['{"color":"control_%d"}', '{"color":"treatment_%d"}'], unit_type: UNIT_TYPE, + **extra) + { + id: id, name: name, unitType: unit_type, iteration: 1, seedHi: 100, seedLo: 200, split: [0.5, 0.5], + trafficSeedHi: 1, trafficSeedLo: 2, trafficSplit: [0.0, 1.0], fullOnVariant: 0, + applications: [{ name: "website" }], audienceStrict: false, audience: nil, + variants: configs.each_with_index.map { |c, i| { name: ("A".ord + i).chr, config: c && format(c, id) } } + }.merge(extra) + end + + def strict_mismatch(id, name) + experiment(id, name, audienceStrict: true, audience: US_ONLY) + end + + def no_unit(id, name) + experiment(id, name, unit_type: "user_id") + end + + def holdout(id, name, seeds) + { + id: id, name: name, unitType: UNIT_TYPE, iteration: 1, seedHi: seeds[0], seedLo: seeds[1], split: [0.1, 0.9], + trafficSeedHi: 0, trafficSeedLo: 0, trafficSplit: [0.0, 1.0], fullOnVariant: 0, applications: [], + variants: [{ name: "A", config: nil }, { name: "B", config: nil }], audienceStrict: false, audience: nil, + holdoutType: "full" + } + end + + def create_context(experiments, holdouts: nil, overrides: {}, country: "GB") + payload = { experiments: experiments } + payload[:holdouts] = holdouts unless holdouts.nil? + json = JSON.generate(payload) + data = DefaultContextDataDeserializer.new.deserialize(json, 0, json.length) + config = ContextConfig.create + config.set_units(UNIT_TYPE => UID) + config.set_overrides(overrides) + context = Context.create(clock, config, OpenStruct.new(data_future: data, success?: true), + double("ContextDataProvider"), event_handler, event_logger, DefaultVariableParser.new, + AudienceMatcher.new(DefaultAudienceDeserializer.new), + application: "website", environment: "production") + context.set_attribute("country", country) + context + end + + # [name, variant, assigned, overridden, rule_override] + def exposures_of(context) + context.publish + published.flat_map { |event| event.exposures || [] }.map do |e| + [e.name, e.variant, e.assigned, e.overridden, e.rule_override] + end + end + + def assigned(name, variant = VARIANT) + [name, variant, true, false, false] + end + + describe "a lower-id candidate the unit is not in" do + it "reads from and exposes only the assigned higher-id candidate after a strict audience mismatch" do + context = create_context([strict_mismatch(1, "exp_low"), experiment(2, "exp_high")]) + + expect(context.variable_value("color", "default")).to eq("treatment_2") + expect(context.pending_count).to eq(1) + expect(exposures_of(context)).to eq([assigned("exp_high")]) + end + + it "reads from and exposes only the assigned higher-id candidate when its unit type is not set" do + context = create_context([no_unit(1, "exp_low"), experiment(2, "exp_high")]) + + expect(context.variable_value("color", "default")).to eq("treatment_2") + expect(context.pending_count).to eq(1) + expect(exposures_of(context)).to eq([assigned("exp_high")]) + end + + it "orders the candidates by id, not payload order" do + context = create_context([experiment(2, "exp_high"), strict_mismatch(1, "exp_low")]) + + expect(context.variable_value("color", "default")).to eq("treatment_2") + expect(exposures_of(context)).to eq([assigned("exp_high")]) + end + + it "still exposes the loser through its own treatment call" do + context = create_context([strict_mismatch(1, "exp_low"), experiment(2, "exp_high")]) + + context.variable_value("color", "default") + context.treatment("exp_low") + expect(exposures_of(context)).to eq([assigned("exp_high"), ["exp_low", 0, false, false, false]]) + end + end + + describe "a winner whose variant lacks the key" do + it "returns the default and exposes only the winner, never a later candidate" do + context = create_context([experiment(1, "exp_low", configs: ['{"color":"control_%d"}', '{"other":"x"}']), + experiment(2, "exp_high")]) + + expect(context.variable_value("color", "default")).to eq("default") + expect(context.pending_count).to eq(1) + expect(exposures_of(context)).to eq([assigned("exp_low")]) + end + + it "returns the default when the winner's variant has no config at all" do + context = create_context([experiment(1, "exp_low", configs: ['{"color":"control_%d"}', nil]), + experiment(2, "exp_high")]) + + expect(context.peek_variable_value("color", "default")).to eq("default") + expect(context.variable_value("color", "default")).to eq("default") + expect(exposures_of(context)).to eq([assigned("exp_low")]) + end + end + + it "returns the default and queues nothing when no candidate is assigned" do + context = create_context([strict_mismatch(1, "exp_low"), no_unit(2, "exp_high")]) + + expect(context.variable_value("color", "default")).to eq("default") + expect(context.pending_count).to eq(0) + expect(exposures_of(context)).to eq([]) + end + + it "returns the default and queues nothing for a key no experiment defines" do + context = create_context([experiment(1, "exp_low")]) + + expect(context.variable_value("missing", "default")).to eq("default") + expect(context.pending_count).to eq(0) + end + + it "queues nothing on peek and returns what variable_value returns" do + context = create_context([strict_mismatch(1, "exp_low"), experiment(2, "exp_high")]) + + expect(context.peek_variable_value("color", "default")).to eq("treatment_2") + expect(context.pending_count).to eq(0) + expect(context.variable_value("color", "default")).to eq("treatment_2") + expect(context.pending_count).to eq(1) + end + + it "does not call the holdout path for candidates without holdouts or already exposed" do + context = create_context([strict_mismatch(1, "exp_low"), experiment(2, "exp_high", holdoutIds: [11])], + holdouts: [holdout(11, "holdout_a", NOT_HOLDING_OUT)]) + context.variable_value("color", "default") + + expect(context).not_to receive(:queue_holdout_exposures) + 3.times { context.variable_value("color", "default") } + end + + it "queues the winner once across repeated reads" do + context = create_context([strict_mismatch(1, "exp_low"), experiment(2, "exp_high")]) + + 3.times { context.variable_value("color", "default") } + expect(exposures_of(context)).to eq([assigned("exp_high")]) + end + + describe "precedence" do + it "lets an override on a candidate the unit is not in win" do + context = create_context([strict_mismatch(1, "exp_skipped"), no_unit(2, "exp_low"), experiment(3, "exp_high")], + overrides: { "exp_low" => 0 }) + + expect(context.variable_value("color", "default")).to eq("control_2") + expect(exposures_of(context)).to eq([["exp_low", 0, false, true, false]]) + end + + it "keeps an assigned lower-id candidate ahead of an override on a higher-id one" do + context = create_context([strict_mismatch(1, "exp_skipped"), experiment(2, "exp_low"), + experiment(3, "exp_high")], overrides: { "exp_high" => 0 }) + + expect(context.variable_value("color", "default")).to eq("treatment_2") + expect(exposures_of(context)).to eq([assigned("exp_low")]) + end + + it "lets a rule on a strict-mismatch candidate win" do + context = create_context([strict_mismatch(1, "exp_skipped"), + strict_mismatch(2, "exp_low").merge(assignmentRules: US_RULE.sub("US\"}", "GB\"}")), + experiment(3, "exp_high")]) + + expect(context.variable_value("color", "default")).to eq("control_2") + expect(exposures_of(context)).to eq([["exp_low", 0, false, false, true]]) + end + + it "keeps an assigned lower-id candidate ahead of a rule on a higher-id one" do + context = create_context([no_unit(1, "exp_skipped"), experiment(2, "exp_low"), + experiment(3, "exp_high", assignmentRules: US_RULE)], country: "US") + + expect(context.variable_value("color", "default")).to eq("treatment_2") + expect(exposures_of(context)).to eq([assigned("exp_low")]) + end + end + + describe "values that are present but falsy" do + [[nil, "null"], [false, "false"], [0, "0"], ["", '""'], [[], "[]"], [{}, "{}"]].each do |value, json| + it "returns #{json} from the winner rather than the default" do + context = create_context([strict_mismatch(1, "exp_low"), + experiment(2, "exp_high", configs: ['{"color":1}', "{\"color\":#{json}}"])]) + + expect(context.peek_variable_value("color", "default")).to eq(value) + expect(context.variable_value("color", "default")).to eq(value) + expect(exposures_of(context)).to eq([assigned("exp_high")]) + end + end + end + + # java-sdk fires the applicable holdouts of every candidate visited on a + # non-peek read, while only the winner gets its own exposure. + describe "a refresh that moves the key while a read walks the candidates" do + # The first candidate (strict mismatch) is covered by a holdout; its + # holdout exposure is logged mid-walk, and the logger refreshes there. + # The refresh moves "color" from exp_b to exp_c, so the read must return + # and expose as one snapshot alone would: blue from exp_b, or green from + # exp_c, never the default with an exp_b exposure. + it "returns a value and exposes an experiment from one snapshot" do + before = [strict_mismatch(1, "exp_a").merge(holdoutIds: [9]), + experiment(2, "exp_b", configs: ['{"color":"blue"}', '{"color":"blue"}']), + experiment(3, "exp_c", configs: ['{"shade":"green"}', '{"shade":"green"}'])] + after = [strict_mismatch(1, "exp_a").merge(holdoutIds: [9]), + experiment(2, "exp_b", configs: ['{"shade":"blue"}', '{"shade":"blue"}']), + experiment(3, "exp_c", configs: ['{"color":"green"}', '{"color":"green"}'])] + holdouts = [holdout(9, "holdout_a", NOT_HOLDING_OUT)] + refreshed = JSON.generate(experiments: after, holdouts: holdouts) + provider = double("ContextDataProvider") + allow(provider).to receive(:context_data) do + OpenStruct.new(data_future: DefaultContextDataDeserializer.new.deserialize(refreshed, 0, refreshed.length), + success?: true) + end + holder = {} + logger = double("ContextEventLogger") + allow(logger).to receive(:handle_event) do |type, data| + if type == ContextEventLogger::EVENT_TYPE::EXPOSURE && data.name == "holdout_a" && !holder[:done] + holder[:done] = true + holder[:context].refresh + end + end + payload = JSON.generate(experiments: before, holdouts: holdouts) + data = DefaultContextDataDeserializer.new.deserialize(payload, 0, payload.length) + config = ContextConfig.create + config.set_units(UNIT_TYPE => UID) + context = Context.create(clock, config, OpenStruct.new(data_future: data, success?: true), provider, + event_handler, logger, DefaultVariableParser.new, + AudienceMatcher.new(DefaultAudienceDeserializer.new), + application: "website", environment: "production") + context.set_attribute("country", "GB") + holder[:context] = context + + value = context.variable_value("color", "default") + exposed = exposures_of(context).map(&:first) + expect(holder[:done]).to be true + expect([[value, exposed]]).to include(["blue", %w[holdout_a exp_b]]).or include(["green", %w[holdout_a exp_c]]) + end + + # The refresh lands after the walk has read its candidates and before it + # resolves the first one: the walk must start again on the new state + # instead of finishing the old candidate list against new experiments. + it "resolves every candidate from the snapshot it read them from" do + before = [experiment(1, "exp_a", audienceStrict: true, audience: US_ONLY), + experiment(2, "exp_b", configs: ['{"color":"blue"}', '{"color":"blue"}']), + experiment(3, "exp_c", configs: ['{"shade":"green"}', '{"shade":"green"}'])] + after = [experiment(1, "exp_a", audienceStrict: true, audience: US_ONLY), + experiment(2, "exp_b", configs: ['{"shade":"blue"}', '{"shade":"blue"}']), + experiment(3, "exp_c", configs: ['{"color":"green"}', '{"color":"green"}'])] + refreshed = JSON.generate(experiments: after) + provider = double("ContextDataProvider") + allow(provider).to receive(:context_data) do + OpenStruct.new(data_future: DefaultContextDataDeserializer.new.deserialize(refreshed, 0, refreshed.length), + success?: true) + end + payload = JSON.generate(experiments: before) + data = DefaultContextDataDeserializer.new.deserialize(payload, 0, payload.length) + config = ContextConfig.create + config.set_units(UNIT_TYPE => UID) + context = Context.create(clock, config, OpenStruct.new(data_future: data, success?: true), provider, + event_handler, event_logger, DefaultVariableParser.new, + AudienceMatcher.new(DefaultAudienceDeserializer.new), + application: "website", environment: "production") + context.set_attribute("country", "GB") + refreshed_once = false + allow(context).to receive(:assignment).and_wrap_original do |original, name| + unless refreshed_once + refreshed_once = true + context.refresh + end + original.call(name) + end + + value = context.variable_value("color", "default") + expect(refreshed_once).to be true + expect([[value, exposures_of(context).map(&:first)]]).to include(["blue", ["exp_b"]]) + .or include(["green", ["exp_c"]]) + end + + # A peek walks the same candidates and exposes nothing; the refresh + # lands from the audience matcher evaluating the first candidate. + it "peeks a value from one snapshot" do + before = [strict_mismatch(1, "exp_a"), + experiment(2, "exp_b", configs: ['{"color":"blue"}', '{"color":"blue"}']), + experiment(3, "exp_c", configs: ['{"shade":"green"}', '{"shade":"green"}'])] + after = [strict_mismatch(1, "exp_a"), + experiment(2, "exp_b", configs: ['{"shade":"blue"}', '{"shade":"blue"}']), + experiment(3, "exp_c", configs: ['{"color":"green"}', '{"color":"green"}'])] + refreshed = JSON.generate(experiments: after) + provider = double("ContextDataProvider") + allow(provider).to receive(:context_data) do + OpenStruct.new(data_future: DefaultContextDataDeserializer.new.deserialize(refreshed, 0, refreshed.length), + success?: true) + end + holder = {} + matcher = AudienceMatcher.new(DefaultAudienceDeserializer.new) + evaluate = matcher.method(:evaluate) + matcher.define_singleton_method(:evaluate) do |audience, attributes| + result = evaluate.call(audience, attributes) + if holder[:armed] && !holder[:done] + holder[:done] = true + holder[:context].refresh + end + result + end + payload = JSON.generate(experiments: before) + data = DefaultContextDataDeserializer.new.deserialize(payload, 0, payload.length) + config = ContextConfig.create + config.set_units(UNIT_TYPE => UID) + context = Context.create(clock, config, OpenStruct.new(data_future: data, success?: true), provider, + event_handler, event_logger, DefaultVariableParser.new, matcher, + application: "website", environment: "production") + context.set_attribute("country", "GB") + holder[:context] = context + holder[:armed] = true + + expect(%w[blue green]).to include(context.peek_variable_value("color", "default")) + expect(holder[:done]).to be true + expect(context.pending_count).to eq(0) + end + + # The refresh (from the matcher, mid-walk) gives exp_b a holdout no + # standing walk visits. + it "exposes no holdout of a candidate visited only by a discarded walk" do + holdouts_before = [holdout(9, "holdout_a", NOT_HOLDING_OUT)] + before = [strict_mismatch(1, "exp_a").merge(holdoutIds: [9]), + experiment(2, "exp_b", configs: ['{"color":"blue"}', '{"color":"blue"}']), + experiment(3, "exp_c", configs: ['{"shade":"green"}', '{"shade":"green"}'])] + after = [strict_mismatch(1, "exp_a").merge(holdoutIds: [9]), + experiment(2, "exp_b", configs: ['{"shade":"blue"}', '{"shade":"blue"}'], holdoutIds: [8]), + experiment(3, "exp_c", configs: ['{"color":"green"}', '{"color":"green"}'])] + holdouts_after = [holdout(8, "b_only", NOT_HOLDING_OUT), holdout(9, "holdout_a", NOT_HOLDING_OUT)] + refreshed = JSON.generate(experiments: after, holdouts: holdouts_after) + provider = double("ContextDataProvider") + allow(provider).to receive(:context_data) do + OpenStruct.new(data_future: DefaultContextDataDeserializer.new.deserialize(refreshed, 0, refreshed.length), + success?: true) + end + holder = {} + matcher = AudienceMatcher.new(DefaultAudienceDeserializer.new) + evaluate = matcher.method(:evaluate) + matcher.define_singleton_method(:evaluate) do |audience, attributes| + result = evaluate.call(audience, attributes) + if holder[:armed] && !holder[:done] + holder[:done] = true + holder[:context].refresh + end + result + end + payload = JSON.generate(experiments: before, holdouts: holdouts_before) + data = DefaultContextDataDeserializer.new.deserialize(payload, 0, payload.length) + config = ContextConfig.create + config.set_units(UNIT_TYPE => UID) + context = Context.create(clock, config, OpenStruct.new(data_future: data, success?: true), provider, + event_handler, event_logger, DefaultVariableParser.new, matcher, + application: "website", environment: "production") + context.set_attribute("country", "GB") + holder[:context] = context + holder[:armed] = true + + value = context.variable_value("color", "default") + expect(holder[:done]).to be true + expect([[value, exposures_of(context).map(&:first)]]).to include(["green", %w[holdout_a exp_c]]) + end + + %i[variable_value peek_variable_value].each do |read| + it "#{read} stops after three walks a refresh overtook" do + # A new iteration per refresh makes every walk re-evaluate exp_a. + snapshot = lambda do |owner, iteration| + json = JSON.generate(holdouts: [holdout(9, "holdout_a", NOT_HOLDING_OUT)], experiments: [ + strict_mismatch(1, "exp_a").merge(holdoutIds: [9], iteration: iteration), + experiment(2, "exp_b", configs: [owner == :b ? '{"color":"blue"}' : '{"shade":"blue"}'] * 2), + experiment(3, "exp_c", configs: [owner == :c ? '{"color":"green"}' : '{"shade":"green"}'] * 2) + ]) + DefaultContextDataDeserializer.new.deserialize(json, 0, json.length) + end + # exp_b keeps the key: a walk that returned its last overtaken winner + # would give blue, so only the exhaustion default passes. + owners = %i[b b].cycle + refreshes = 0 + provider = double("ContextDataProvider") + allow(provider).to receive(:context_data) do + refreshes += 1 + OpenStruct.new(data_future: snapshot.call(owners.next, refreshes + 1), success?: true) + end + holder = {} + matcher = AudienceMatcher.new(DefaultAudienceDeserializer.new) + evaluate = matcher.method(:evaluate) + matcher.define_singleton_method(:evaluate) do |audience, attributes| + result = evaluate.call(audience, attributes) + if holder[:armed] + raise "no progress after #{refreshes} refreshes" if refreshes > 10 + + holder[:context].refresh + end + result + end + config = ContextConfig.create + config.set_units(UNIT_TYPE => UID) + context = Context.create(clock, config, OpenStruct.new(data_future: snapshot.call(:b, 1), success?: true), + provider, event_handler, event_logger, DefaultVariableParser.new, matcher, + application: "website", environment: "production") + context.set_attribute("country", "GB") + holder[:context] = context + holder[:armed] = true + + expect(context.public_send(read, "color", "default")).to eq("default") + expect(refreshes).to eq(3) + holder[:armed] = false + expect(exposures_of(context)).to eq([]) + end + end + + # The variable read pauses before exp_high and the peek before + # exp_size; then one finishes first, then the other. + %i[peek_first variable_first].each do |order| + it "keeps each concurrent read's collected holdouts its own (#{order.to_s.tr("_", " ")})" do + # "size" is shared too, so the peek walks several candidates. + experiments = [strict_mismatch(1, "exp_low").merge(holdoutIds: [11]), + experiment(2, "exp_high"), + experiment(3, "exp_size", configs: ['{"size":1}', '{"size":2}']), + experiment(4, "exp_size_too", configs: ['{"size":3}', '{"size":4}'])] + context = create_context(experiments, holdouts: [holdout(11, "holdout_a", NOT_HOLDING_OUT)]) + gates = { variable: [Queue.new, Queue.new], peek: [Queue.new, Queue.new] } + pause_at = { variable: "exp_high", peek: "exp_size" } + allow(context).to receive(:assignment).and_wrap_original do |original, name| + role = Thread.current[:role] + if role && name.to_s == pause_at[role] && !Thread.current[:paused] + Thread.current[:paused] = true + gates[role][0] << true + gates[role][1].pop + end + original.call(name) + end + read = Thread.new do + Thread.current[:role] = :variable + context.variable_value("color", "default") + end + peek = Thread.new do + Thread.current[:role] = :peek + context.peek_variable_value("size", 0) + end + pending_after_peek = nil + begin + Timeout.timeout(5) { gates[:variable][0].pop } + Timeout.timeout(5) { gates[:peek][0].pop } + if order == :peek_first + gates[:peek][1] << true + Timeout.timeout(5) { peek.join } + pending_after_peek = context.pending_count + gates[:variable][1] << true + else + gates[:variable][1] << true + Timeout.timeout(5) { read.join } + pending_after_peek = context.pending_count - 2 + gates[:peek][1] << true + end + Timeout.timeout(5) { [read, peek].each(&:join) } + ensure + gates.each_value { |(_, go)| go << true } + [read, peek].each { |t| t.join(1) || t.kill } + end + + expect(peek.value).to eq(2) + expect(read.value).to eq("treatment_2") + expect(pending_after_peek).to eq(0) + expect(exposures_of(context)).to eq([assigned("holdout_a"), assigned("exp_high")]) + end + end + + # Two exposing reads on two shared keys, interleaved outside the locks: + # each collects and exposes its own loser's holdout. + it "keeps each of two concurrent variable_value reads' collected holdouts its own" do + experiments = [strict_mismatch(1, "a_low").merge(holdoutIds: [11]), experiment(2, "a_high"), + experiment(3, "b_low", configs: ['{"size":1}', '{"size":1}'], audienceStrict: true, + audience: US_ONLY, holdoutIds: [12]), + experiment(4, "b_high", configs: ['{"size":2}', '{"size":2}'])] + context = create_context(experiments, holdouts: [holdout(11, "h_a", NOT_HOLDING_OUT), + holdout(12, "h_b", NOT_HOLDING_OUT)]) + paused = Queue.new + resume = Queue.new + allow(context).to receive(:assignment).and_wrap_original do |original, name| + if Thread.current[:role] == :a && name.to_s == "a_high" && !Thread.current[:paused] + Thread.current[:paused] = true + paused << true + resume.pop + end + original.call(name) + end + first = Thread.new do + Thread.current[:role] = :a + context.variable_value("color", "default") + end + begin + Timeout.timeout(5) { paused.pop } + second = Thread.new { context.variable_value("size", 0) } + Timeout.timeout(5) { second.join } + ensure + resume << true + first.join(5) || first.kill + end + + expect([first.value, second.value]).to eq(%w[treatment_2] + [2]) + expect(exposures_of(context).map(&:first).sort).to eq(%w[a_high b_high h_a h_b]) + end + + # The refresh lands from the audience matcher while the walk evaluates a + # key's only candidate, and moves the key to another experiment: the + # walk restarts, so the old candidate's holdout is never exposed. + it "exposes no holdout of a single candidate a refresh overtook" do + before = [experiment(1, "only_a", configs: ['{"color":1}', '{"color":1}'], + audience: US_ONLY, holdoutIds: [11]), + experiment(2, "only_b", configs: ['{"shade":2}', '{"shade":2}'])] + after = [experiment(1, "only_a", configs: ['{"shade":1}', '{"shade":1}'], + audience: US_ONLY, holdoutIds: [11]), + experiment(2, "only_b", configs: ['{"color":2}', '{"color":2}'])] + holdouts = [holdout(11, "h_a", NOT_HOLDING_OUT)] + refreshed = JSON.generate(experiments: after, holdouts: holdouts) + provider = double("ContextDataProvider") + allow(provider).to receive(:context_data) do + OpenStruct.new(data_future: DefaultContextDataDeserializer.new.deserialize(refreshed, 0, refreshed.length), + success?: true) + end + holder = {} + matcher = AudienceMatcher.new(DefaultAudienceDeserializer.new) + evaluate = matcher.method(:evaluate) + matcher.define_singleton_method(:evaluate) do |audience, attributes| + result = evaluate.call(audience, attributes) + if holder[:armed] && !holder[:done] + holder[:done] = true + holder[:context].refresh + end + result + end + payload = JSON.generate(experiments: before, holdouts: holdouts) + data = DefaultContextDataDeserializer.new.deserialize(payload, 0, payload.length) + config = ContextConfig.create + config.set_units(UNIT_TYPE => UID) + context = Context.create(clock, config, OpenStruct.new(data_future: data, success?: true), provider, + event_handler, event_logger, DefaultVariableParser.new, matcher, + application: "website", environment: "production") + context.set_attribute("country", "GB") + holder[:context] = context + holder[:armed] = true + + expect(context.variable_value("color", 0)).to eq(2) + expect(holder[:done]).to be true + expect(exposures_of(context).map(&:first)).to eq(["only_b"]) + end + end + + describe "holdouts" do + it "exposes a visited loser's holdout but not the loser itself" do + context = create_context([strict_mismatch(1, "exp_low").merge(holdoutIds: [11]), experiment(2, "exp_high")], + holdouts: [holdout(11, "holdout_a", NOT_HOLDING_OUT)]) + + expect(context.variable_value("color", "default")).to eq("treatment_2") + expect(exposures_of(context)).to eq([assigned("holdout_a"), assigned("exp_high")]) + end + + it "does not expose the holdouts of candidates after the winner" do + context = create_context([no_unit(1, "exp_skipped"), experiment(2, "exp_low"), + experiment(3, "exp_high", holdoutIds: [11])], + holdouts: [holdout(11, "holdout_a", NOT_HOLDING_OUT)]) + + expect(context.variable_value("color", "default")).to eq("treatment_2") + expect(exposures_of(context)).to eq([assigned("exp_low")]) + end + + it "reads a held-out candidate's control only when no candidate is assigned" do + context = create_context([experiment(1, "exp_low", holdoutIds: [11]), strict_mismatch(2, "exp_high")], + holdouts: [holdout(11, "holdout_a", HOLDING_OUT)]) + + expect(context.variable_value("color", "default")).to eq("control_1") + expect(exposures_of(context)).to eq([["holdout_a", 0, true, false, false]]) + end + + it "exposes a visited loser's holdout once across repeated reads" do + context = create_context([strict_mismatch(1, "exp_low").merge(holdoutIds: [11]), experiment(2, "exp_high")], + holdouts: [holdout(11, "holdout_a", NOT_HOLDING_OUT)]) + + 3.times { expect(context.variable_value("color", "default")).to eq("treatment_2") } + expect(exposures_of(context)).to eq([assigned("holdout_a"), assigned("exp_high")]) + end + + it "exposes only a loser's still-unexposed holdout when another is already exposed" do + context = create_context([strict_mismatch(1, "exp_low").merge(holdoutIds: [11, 12]), experiment(2, "exp_high"), + experiment(5, "exp_other", configs: ['{"size":1}', '{"size":2}'], holdoutIds: [11])], + holdouts: [holdout(11, "holdout_a", NOT_HOLDING_OUT), + holdout(12, "holdout_b", NOT_HOLDING_OUT)]) + context.treatment("exp_other") + + expect(context.variable_value("color", "default")).to eq("treatment_2") + expect(exposures_of(context)).to eq([assigned("exp_other"), assigned("holdout_a"), assigned("holdout_b"), + assigned("exp_high")]) + end + + it "queues the winner's holdouts before the winner, as java-sdk does" do + context = create_context([strict_mismatch(1, "exp_low").merge(holdoutIds: [11]), + experiment(2, "exp_high", holdoutIds: [12])], + holdouts: [holdout(11, "holdout_a", NOT_HOLDING_OUT), + holdout(12, "holdout_b", NOT_HOLDING_OUT)]) + + expect(context.variable_value("color", "default")).to eq("treatment_2") + 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)]) + + 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 "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(clock).not_to receive(:to_i) + 3.times { context.variable_value("color", "default") } + end + + it "queues no loser holdout exposure once a logger callback closed the context" do + context = create_context([strict_mismatch(1, "exp_low").merge(holdoutIds: [11]), + strict_mismatch(2, "exp_mid").merge(holdoutIds: [12]), experiment(3, "exp_high")], + holdouts: [holdout(11, "holdout_a", NOT_HOLDING_OUT), + holdout(12, "holdout_b", NOT_HOLDING_OUT)]) + allow(event_logger).to receive(:handle_event) do |_type, data| + context.close if data.is_a?(Exposure) && data.name == "holdout_a" + end + + expect { context.variable_value("color", "default") }.to raise_error(IllegalStateException, /closed/) + # close published what was queued before it; nothing was queued after. + expect(published.flat_map(&:exposures).map(&:name)).to eq(["holdout_a"]) + expect(context.pending_count).to eq(0) + end + + it "fires nothing on peek" do + context = create_context([strict_mismatch(1, "exp_low").merge(holdoutIds: [11]), experiment(2, "exp_high")], + holdouts: [holdout(11, "holdout_a", NOT_HOLDING_OUT)]) + + expect(context.peek_variable_value("color", "default")).to eq("treatment_2") + expect(context.pending_count).to eq(0) + end + + it "does not enter the holdout path on warm reads past an exposed 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(context).not_to receive(:queue_holdout_exposures) + 3.times { expect(context.variable_value("color", "default")).to eq("treatment_2") } + end + + # The override's holdout arm can't be computed before its unit is set; + # the next read after set_unit exposes it (as java-sdk), also when the + # key is shared with another experiment. + [1, 2].each do |count| + it "exposes an override's late holdout arm on a #{count}-candidate key" do + experiments = [experiment(1, "overridden", unit_type: "user_id", holdoutIds: [11])] + experiments << experiment(2, "other") if count == 2 + late = holdout(11, "holdout_user", NOT_HOLDING_OUT).merge(unitType: "user_id") + context = create_context(experiments, holdouts: [late], overrides: { "overridden" => 1 }) + expect(context.variable_value("color", "default")).to eq("treatment_1") + context.set_unit("user_id", "u9") + expect(context.variable_value("color", "default")).to eq("treatment_1") + + expect(exposures_of(context).map(&:first)).to eq(%w[overridden holdout_user]) + end + end + + [["user_id", "never set"], [nil, "no unit type"]].each do |unit_type, label| + it "reads an override with holdouts whose unit is #{label} without entering the holdout path again" do + late = holdout(11, "holdout_user", NOT_HOLDING_OUT).merge(unitType: "user_id") + context = create_context([experiment(1, "overridden", unit_type: unit_type, holdoutIds: [11]), + experiment(2, "other")], + holdouts: [late], overrides: { "overridden" => 1 }) + expect(context.variable_value("color", "default")).to eq("treatment_1") + + expect(context).not_to receive(:queue_holdout_exposures) + 2.times { expect(context.variable_value("color", "default")).to eq("treatment_1") } + expect(exposures_of(context)).to eq([["overridden", 1, false, true, false]]) + end + end + + it "does not check pending holdouts on warm reads of an exposed, not overridden winner" do + context = create_context([experiment(1, "exp_low", holdoutIds: [11]), experiment(2, "exp_high", holdoutIds: [11])], + holdouts: [holdout(11, "holdout_a", NOT_HOLDING_OUT)]) + context.variable_value("color", "default") + + expect(context).not_to receive(:holdouts_pending?) + 2.times { expect(context.variable_value("color", "default")).to eq("treatment_1") } + end + end + end +end diff --git a/spec/context_spec.rb b/spec/context_spec.rb index 2d2b8d08..e7fd171d 100644 --- a/spec/context_spec.rb +++ b/spec/context_spec.rb @@ -17,6 +17,7 @@ require "audience_matcher" require "json/unit" require "logger" +require "timeout" RSpec.describe Context do let(:units) { @@ -105,7 +106,7 @@ let(:publish_future) { OpenStruct.new(success?: true) } let(:event_handler) do - ev = instance_double(ContextPublisher) + ev = instance_double(Absmartly::ContextPublisher) allow(ev).to receive(:publish).and_return(publish_future) ev end @@ -235,8 +236,6 @@ def faraday_response(content) expect { context.variable_keys }.to raise_error(IllegalStateException, not_ready_message) expect { context.custom_field_keys }.to raise_error(IllegalStateException, not_ready_message) expect { context.custom_field_value("exp_test_ab", "country") }.to raise_error(IllegalStateException, not_ready_message) - expect { context.publish }.to raise_error(IllegalStateException, not_ready_message) - expect { context.refresh }.to raise_error(IllegalStateException, not_ready_message) expect { context.data @@ -294,8 +293,117 @@ def faraday_response(content) expect { context.variable_keys }.to raise_error(IllegalStateException, closed_message) expect { context.custom_field_keys }.to raise_error(IllegalStateException, closed_message) expect { context.refresh }.to raise_error(IllegalStateException, closed_message) - # experiments only requires readiness, like the JavaScript SDK. + expect { context.experiments }.to raise_error(IllegalStateException, closed_message) + expect { context.set_override("exp_test_ab", 2) }.to raise_error(IllegalStateException, closed_message) + expect { context.set_overrides("exp_test_ab": 2) }.to raise_error(IllegalStateException, closed_message) + end + + it "keeps experiments and overrides usable after finalize, like the JavaScript SDK" do + context = create_ready_context + allow(event_handler).to receive(:publish).and_return(nil) + context.finalize + + closed_message = "ABSmartly Context is closed" expect(context.experiments).to eq(data.experiments.map(&:name)) + expect { context.set_override("exp_test_ab", 2) }.not_to raise_error + expect { context.set_overrides("exp_test_ab": 2) }.not_to raise_error + expect { context.treatment("exp_test_ab") }.to raise_error(IllegalStateException, closed_message) + end + + it "returns the event logger's result from close and a successful refresh, as in v1.3.0" do + logger = Class.new(ContextEventLogger) do + def handle_event(event, _data) + "logged #{event}" + end + end.new + config = ContextConfig.create + config.set_units(units) + allow(data_provider).to receive(:context_data).and_return(data_future_ready) + context = Context.create(clock, config, data_future_ready, data_provider, event_handler, logger, + variable_parser, audience_matcher) + + expect(context.refresh).to eq("logged refresh") + expect(context.close).to eq("logged close") + expect(context.close).to be_nil + end + + it "returns the event logger's result from a failed refresh and keeps the data, as in v1.3.0" do + logger = Class.new(ContextEventLogger) do + def handle_event(event, data) + "logged #{event} #{data}" + end + end.new + config = ContextConfig.create + config.set_units(units) + context = Context.create(clock, config, data_future_ready, data_provider, event_handler, logger, + variable_parser, audience_matcher) + allow(data_provider).to receive(:context_data).and_return(failure_future) + + expect(context.refresh).to eq("logged error FAILED") + expect(context.failed?).to be_falsey + end + + it "close stops after one extra publish when a logger keeps queueing events" do + config = ContextConfig.create + config.set_units(units) + holder = {} + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + holder[:context]&.track("again", nil) if event == ContextEventLogger::EVENT_TYPE::PUBLISH + end + end.new + publishes = 0 + handler = instance_double(Absmartly::ContextPublisher) + allow(handler).to receive(:publish) { publishes += 1; nil } + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + + expect { Timeout.timeout(5) { holder[:context].close } } + .to raise_error(StandardError, "Events queued while closing; retry close or finalize") + expect(holder[:context].closed?).to be false + expect(holder[:context].pending_count).to eq(1) + expect(publishes).to eq(2) + end + + it "retains events accepted during the last seal pass for a retry" do + [:close, :finalize].each do |method| + config = ContextConfig.create + config.set_units(units) + sent = [] + callbacks = 0 + holder = {} + logger = Object.new + logger.define_singleton_method(:handle_event) do |event, _data| + if event == ContextEventLogger::EVENT_TYPE::PUBLISH && callbacks < 2 + callbacks += 1 + holder[:context].track("callback_#{callbacks}", nil) + end + end + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + sent.concat(event.goals.map(&:name)) + nil + end + context = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context] = context + context.track("initial", nil) + expect { Timeout.timeout(5) { context.public_send(method) } }.to raise_error(StandardError, /retry/) + expect(context.pending_count).to eq(1) + expect(context.closed?).to be false + Timeout.timeout(5) { context.public_send(method) } + expect(sent).to eq(["initial", "callback_1", "callback_2"]) + expect(context.closed?).to be true + end + end + + it "publishes and refreshes before the context is ready, as in v1.3.0" do + context = create_context(data_future) + expect(context.ready?).to be_falsey + expect { context.publish }.not_to raise_error + allow(data_provider).to receive(:context_data).and_return(data_future_ready) + expect { context.refresh }.not_to raise_error end it "experiments" do @@ -323,19 +431,20 @@ def faraday_response(content) expect(context.get_units[:db_user_id]).to eq(125) end - it "numeric uid assigns and publishes like its canonical string" do + it "numeric uid assigns and publishes like its to_s text, as in v1.3.0" 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("126") + string = make.call("125.75") %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").key) - expect(VariantAssigner.new(125.75).key).to eq(VariantAssigner.new("126").key) + 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).key).to eq(VariantAssigner.new("125").key) end it "set unit converts symbols and string-like uids to strings, as in v1.3.0" do @@ -382,6 +491,1630 @@ def to_s }.to raise_error(IllegalStateException, "Unit 'db_user_id' UID must not be blank.") end + it "passes a custom 1.3.0-style matcher the attribute keys the caller used" do + seen = [] + matcher = Class.new do + define_method(:evaluate) do |_audience, attributes| + seen << attributes.keys + Struct.new(:result).new(attributes[:age].to_i >= 20) + end + end.new + config = ContextConfig.create + config.set_units(units) + context = Context.create(clock, config, audience_strict_data_future_ready, data_provider, event_handler, + event_logger, variable_parser, matcher, application: "website", environment: "prod") + context.set_attribute(:age, 21) + context.set_attribute("environment", "staging") + + expect(context.peek_treatment("exp_test_ab")).not_to eq(0) + expect(seen.last).to contain_exactly(:age, "application", "environment") + expect(seen.last.index("environment")).to be > seen.last.index(:age) + end + + it "evaluates the last value set for a repeated attribute name" do + config = ContextConfig.create + config.set_units(units) + context = Context.create(clock, config, audience_strict_data_future_ready, data_provider, event_handler, + event_logger, variable_parser, audience_matcher) + context.set_attribute("age", 10) + context.set_attribute("age", 25) + + expect(context.peek_treatment("exp_test_ab")).not_to eq(0) + end + + it "keeps the system entry when a user attribute name is neither a String nor a Symbol" do + seen = nil + matcher = Class.new do + define_method(:evaluate) do |_audience, attributes| + seen = attributes + Struct.new(:result).new(true) + end + end.new + name = Object.new + def name.to_s + "environment" + end + config = ContextConfig.create + config.set_units(units) + context = Context.create(clock, config, audience_strict_data_future_ready, data_provider, event_handler, + event_logger, variable_parser, matcher, application: "website", environment: "prod") + context.set_attribute(name, "staging") + context.peek_treatment("exp_test_ab") + + expect(seen).to eq("application" => "website", "environment" => "prod", name => "staging") + end + + describe "the built-in audience evaluator with an attribute set under both spellings" do + def strict_context + config = ContextConfig.create + config.set_units(units) + Context.create(clock, config, audience_strict_data_future_ready, data_provider, event_handler, + event_logger, variable_parser, audience_matcher) + end + + it "uses the latest value on first resolution" do + context = strict_context + context.set_attribute("age", 10) + context.set_attribute(:age, 25) + expect(context.peek_treatment("exp_test_ab")).not_to eq(0) + + context = strict_context + context.set_attribute("age", 25) + context.set_attribute(:age, 10) + expect(context.peek_treatment("exp_test_ab")).to eq(0) + end + + it "uses the latest value when revalidating a cached assignment" do + context = strict_context + context.set_attribute("age", 10) + expect(context.peek_treatment("exp_test_ab")).to eq(0) + context.set_attribute(:age, 25) + expect(context.peek_treatment("exp_test_ab")).not_to eq(0) + context.set_attribute("age", 10) + expect(context.peek_treatment("exp_test_ab")).to eq(0) + end + + it "evaluates an attribute name that is neither a String nor a Symbol by its text" do + name = Object.new + def name.to_s + "age" + end + context = strict_context + context.set_attribute(name, 25) + expect(context.peek_treatment("exp_test_ab")).not_to eq(0) + + context = strict_context + context.set_attribute("age", 25) + context.set_attribute(name, 10) + expect(context.peek_treatment("exp_test_ab")).to eq(0) + end + end + + it "passes both String and Symbol user keys to an AudienceMatcher subclass, as in v1.3.0" do + seen = nil + matcher = Class.new(AudienceMatcher) do + define_method(:evaluate) do |audience, attributes| + seen = attributes + super(audience, attributes) + end + end.new(DefaultAudienceDeserializer.new) + config = ContextConfig.create + config.set_units(units) + context = Context.create(clock, config, audience_strict_data_future_ready, data_provider, event_handler, + event_logger, variable_parser, matcher) + context.set_attribute("age", 10) + context.set_attribute(:age, 25) + context.peek_treatment("exp_test_ab") + + expect(seen).to eq("age" => 10, :age => 25) + end + + it "builds no per-claim block on a first exposure" do + contexts = Array.new(50) { create_ready_context.tap { |c| c.peek_treatment("exp_test_ab") } } + GC.disable + begin + before = ObjectSpace.each_object(Proc).count + contexts.each { |c| c.treatment("exp_test_ab") } + created = ObjectSpace.each_object(Proc).count - before + ensure + GC.enable + end + expect(created).to be < 50 + end + + it "allocates no more on warmed treatment and variable reads than one exposed read needs" do + context = create_ready_context + context.treatment("exp_test_ab") + context.variable_value("banner.size", "default") + measure = lambda do |&read| + GC.disable + before = GC.stat(:total_allocated_objects) + 100.times(&read) + GC.stat(:total_allocated_objects) - before + ensure + GC.enable + end + expect(measure.call { context.treatment("exp_test_ab") }).to be <= 100 + expect(measure.call { context.variable_value("banner.size", "default") }).to be <= 100 + end + + it "lets a timeout interrupt a treatment waiting for the assignment lock" do + release = Queue.new + holding = Queue.new + matcher = Class.new do + define_method(:evaluate) do |_audience, _attributes| + if Thread.current[:hold] + holding << true + # Bounded, so a regression that masks the wait fails instead of hanging. + Timeout.timeout(1.5) { release.pop } rescue nil + end + Struct.new(:result).new(true) + end + end.new + config = ContextConfig.create + config.set_units(units) + context = Context.create(clock, config, audience_strict_data_future_ready, data_provider, event_handler, + event_logger, variable_parser, matcher) + assignment = context.send(:assignment, "exp_test_abc") + holder = Thread.new do + Thread.current[:hold] = true + context.peek_treatment("exp_test_ab") + end + begin + Timeout.timeout(5) { holding.pop } + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + expect { Timeout.timeout(0.3) { context.send(:claim_and_queue_exposure, assignment, "exp_test_abc") } } + .to raise_error(Timeout::Error) + expect(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).to be < 1 + ensure + release << true + holder.join(5) || holder.kill + end + end + + it "keeps the 1.3.0 contract of the public queue_exposure" do + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) { |event, _data| event == ContextEventLogger::EVENT_TYPE::EXPOSURE ? :sentinel : nil } + end.new + config = ContextConfig.create + config.set_units(units) + context = Context.create(clock, config, data_future_ready, data_provider, event_handler, logger, + variable_parser, audience_matcher) + assignment = context.send(:assignment, "exp_test_ab") + + expect(Context.public_method_defined?(:queue_exposure)).to be true + expect(Context.instance_method(:queue_exposure).arity).to eq(1) + expect(context.queue_exposure(assignment)).to eq(:sentinel) + expect(context.queue_exposure(assignment)).to be_nil + expect(context.pending_count).to eq(1) + end + + it "lets a custom matcher directly queue a fresh exposure" do + holder = {} + matcher = Object.new + matcher.define_singleton_method(:evaluate) do |_audience, _attributes| + side = Assignment.new + side.name = "side-exposure" + holder[:context].queue_exposure(side) + Struct.new(:result).new(true) + end + config = ContextConfig.create + config.set_units(units) + context = Context.create(clock, config, audience_strict_data_future_ready, data_provider, event_handler, + event_logger, variable_parser, matcher) + holder[:context] = context + expect(context.peek_treatment("exp_test_ab")).not_to eq(0) + expect(context.pending_count).to eq(1) + expect(context.instance_variable_get(:@exposures).map(&:name)).to eq(["side-exposure"]) + end + + %i[timeout kill].each do |cancel| + it "keeps close guards consistent when #{cancel} interrupts the final seal update" do + context = create_ready_context + source = Context.instance_method(:seal).source_location.first + lines = File.readlines(source) + writes = lines.each_index.select { |index| ["@closed = true", "@sealed_by = event_type"].include?(lines[index].strip) } + expect(writes.size).to eq(2) + target = writes.max + 1 + parked = Queue.new + resume = Queue.new + trace = TracePoint.new(:line) do |tp| + if tp.path == source && tp.lineno == target && Thread.current[:gate] + Thread.current[:gate] = false + parked << true + resume.pop + end + end + trace.enable + worker = Thread.new do + Thread.current[:gate] = true + context.close + rescue Timeout::Error + nil + end + begin + Timeout.timeout(5) { parked.pop } + cancel == :kill ? worker.kill : worker.raise(Timeout::Error) + resume << true + Timeout.timeout(5) { worker.join } + ensure + trace.disable + resume << true + worker.join(1) || worker.kill + end + expect(context.closed?).to be true + expect { context.set_override("exp_test_ab", 1) }.to raise_error(IllegalStateException) + expect { context.experiments }.to raise_error(IllegalStateException) + end + end + + it "keeps both String and Symbol user keys for a custom matcher, as in v1.3.0" do + seen = nil + matcher = Class.new do + define_method(:evaluate) do |_audience, attributes| + seen = attributes + Struct.new(:result).new(attributes.fetch("age", 0) >= 20) + end + end.new + config = ContextConfig.create + config.set_units(units) + context = Context.create(clock, config, audience_strict_data_future_ready, data_provider, event_handler, + event_logger, variable_parser, matcher, application: "website", environment: "prod") + context.set_attribute("age", 21) + context.set_attribute(:age, 22) + context.set_attribute(:environment, "staging") + + expect(context.peek_treatment("exp_test_ab")).not_to eq(0) + expect(seen).to eq("application" => "website", "age" => 21, :age => 22, :environment => "staging") + end + + it "keeps a user String key when the same name is then set as a Symbol, as in v1.3.0" do + seen = nil + matcher = Class.new do + define_method(:evaluate) do |_audience, attributes| + seen = attributes + Struct.new(:result).new(true) + end + end.new + config = ContextConfig.create + config.set_units(units) + context = Context.create(clock, config, audience_strict_data_future_ready, data_provider, event_handler, + event_logger, variable_parser, matcher, application: "website", environment: "prod") + context.set_attribute("environment", "a") + context.set_attribute(:environment, "b") + context.peek_treatment("exp_test_ab") + + expect(seen).to eq("application" => "website", "environment" => "a", :environment => "b") + expect(seen.keys).to eq(["application", "environment", :environment]) + end + + it "keeps a user String key that reuses the configured value object when a Symbol key follows" do + seen = nil + matcher = Class.new do + define_method(:evaluate) do |_audience, attributes| + seen = attributes + Struct.new(:result).new(attributes["environment"] == "prod") + end + end.new + env = "prod" + config = ContextConfig.create + config.set_units(units) + context = Context.create(clock, config, audience_strict_data_future_ready, data_provider, event_handler, + event_logger, variable_parser, matcher, application: "website", environment: env) + context.set_attribute("environment", env) + context.set_attribute(:environment, "staging") + + expect(context.peek_treatment("exp_test_ab")).not_to eq(0) + expect(seen).to eq("application" => "website", "environment" => "prod", :environment => "staging") + end + + it "publish returns normally when a logger's deferred close still has events queued" do + config = ContextConfig.create + config.set_units(units) + holder = {} + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + next unless event == ContextEventLogger::EVENT_TYPE::PUBLISH + + holder[:context].track("again", nil) + holder[:context].close unless holder[:closing] + holder[:closing] = true + end + end.new + handler = instance_double(Absmartly::ContextPublisher) + allow(handler).to receive(:publish).and_return(nil) + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + + expect { Timeout.timeout(5) { holder[:context].publish } }.not_to raise_error + expect(holder[:context].closed?).to be false + expect(holder[:context].pending_count).to be > 0 + end + + it "closes on the next publish when a logger's deferred close hit the pass limit" do + config = ContextConfig.create + config.set_units(units) + holder = { goals: 0 } + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + holder[:events] = (holder[:events] || []) << event + next unless event == ContextEventLogger::EVENT_TYPE::PUBLISH && holder[:goals] < 3 + + holder[:goals] += 1 + holder[:context].track("cb#{holder[:goals]}", nil) + holder[:context].close if holder[:goals] == 1 + end + end.new + handler = instance_double(Absmartly::ContextPublisher) + allow(handler).to receive(:publish).and_return(nil) + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + + Timeout.timeout(5) { holder[:context].publish } + expect(holder[:context].closed?).to be false + Timeout.timeout(5) { holder[:context].publish } + expect(holder[:context].closed?).to be true + expect(holder[:context].pending_count).to eq(0) + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::CLOSE)).to eq(1) + end + + it "carries a deferred finalize as finalize, not close" do + config = ContextConfig.create + config.set_units(units) + holder = { goals: 0 } + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + holder[:events] = (holder[:events] || []) << event + next unless event == ContextEventLogger::EVENT_TYPE::PUBLISH && holder[:goals] < 3 + + holder[:goals] += 1 + holder[:context].track("cb#{holder[:goals]}", nil) + holder[:context].finalize if holder[:goals] == 1 + end + end.new + handler = instance_double(Absmartly::ContextPublisher) + allow(handler).to receive(:publish).and_return(nil) + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + + Timeout.timeout(5) { holder[:context].publish } + expect(holder[:context].closed?).to be false + Timeout.timeout(5) { holder[:context].publish } + expect(holder[:context].finalized?).to be true + expect(holder[:context].pending_count).to eq(0) + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::FINALIZE)).to eq(1) + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::CLOSE)).to eq(0) + expect { holder[:context].set_override("exp_test_ab", 1) }.not_to raise_error + end + + it "keeps a carried close when the next publish is rejected" do + config = ContextConfig.create + config.set_units(units) + holder = { goals: 0 } + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + holder[:events] = (holder[:events] || []) << event + next unless event == ContextEventLogger::EVENT_TYPE::PUBLISH && holder[:goals] < 3 + + holder[:goals] += 1 + holder[:context].track("cb#{holder[:goals]}", nil) + holder[:context].close if holder[:goals] == 1 + end + end.new + responses = [nil, nil, nil, failure_future, nil] + handler = instance_double(Absmartly::ContextPublisher) + allow(handler).to receive(:publish) { responses.shift } + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + + Timeout.timeout(5) { holder[:context].publish } + holder[:context].track("late", nil) + Timeout.timeout(5) { holder[:context].publish } + expect(holder[:context].closed?).to be false + expect(holder[:context].pending_count).to eq(2) + Timeout.timeout(5) { holder[:context].publish } + expect(holder[:context].closed?).to be true + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::CLOSE)).to eq(1) + end + + it "a close from the error callback of a rejected publish seals on the next good publish" do + config = ContextConfig.create + config.set_units(units) + holder = { events: [] } + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + holder[:events] << event + holder[:context].close if event == ContextEventLogger::EVENT_TYPE::ERROR && !holder[:asked] + holder[:asked] = true if event == ContextEventLogger::EVENT_TYPE::ERROR + end + end.new + responses = [StandardError.new("rejected"), nil] + handler = instance_double(Absmartly::ContextPublisher) + allow(handler).to receive(:publish) { responses.shift } + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + + expect(Timeout.timeout(5) { holder[:context].publish }).to be_a(StandardError) + expect(holder[:context].closed?).to be false + expect(holder[:context].pending_count).to eq(1) + Timeout.timeout(5) { holder[:context].publish } + expect(holder[:context].closed?).to be true + expect(holder[:context].pending_count).to eq(0) + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::CLOSE)).to eq(1) + end + + it "a close requested from a publish callback during close stays within close's two passes" do + config = ContextConfig.create + config.set_units(units) + holder = { goals: 0 } + publishes = 0 + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + next unless event == ContextEventLogger::EVENT_TYPE::PUBLISH && holder[:goals] < 10 + + holder[:goals] += 1 + holder[:context].track("cb#{holder[:goals]}", nil) + holder[:context].close + end + end.new + handler = instance_double(Absmartly::ContextPublisher) + allow(handler).to receive(:publish) { publishes += 1; nil } + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + + expect { Timeout.timeout(5) { holder[:context].close } } + .to raise_error(StandardError, "Events queued while closing; retry close or finalize") + expect(publishes).to eq(2) + expect(holder[:context].closed?).to be false + expect(holder[:context].pending_count).to eq(1) + end + + it "keeps a deferred finalize pending when its own publish is rejected" do + config = ContextConfig.create + config.set_units(units) + holder = { goals: 0, events: [] } + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + holder[:events] << event + next unless event == ContextEventLogger::EVENT_TYPE::PUBLISH && holder[:goals] < 1 + + holder[:goals] += 1 + holder[:context].track("cb", nil) + holder[:context].finalize + end + end.new + responses = [nil, failure_future, nil, nil] + handler = instance_double(Absmartly::ContextPublisher) + allow(handler).to receive(:publish) { responses.shift } + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + + expect { Timeout.timeout(5) { holder[:context].publish } }.to raise_error(Exception, "FAILED") + expect(holder[:context].finalized?).to be false + expect(holder[:context].pending_count).to eq(1) + holder[:context].track("late", nil) + Timeout.timeout(5) { holder[:context].publish } + expect(holder[:context].finalized?).to be true + expect(holder[:context].pending_count).to eq(0) + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::FINALIZE)).to eq(1) + end + + it "keeps a deferred finalize pending when a timeout interrupts its own publish" do + config = ContextConfig.create + config.set_units(units) + holder = { goals: 0, events: [], calls: 0 } + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + holder[:events] << event + next unless event == ContextEventLogger::EVENT_TYPE::PUBLISH && holder[:goals] < 1 + + holder[:goals] += 1 + holder[:context].track("followup", nil) + holder[:context].finalize + end + end.new + blocked = Queue.new + handler = Object.new + handler.define_singleton_method(:publish) do |_context, _event| + holder[:calls] += 1 + if holder[:calls] == 2 + blocked << true + sleep + end + OpenStruct.new(success?: true) + end + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + + # A real Timeout.timeout, which unwinds with a non-StandardError + # (Timeout::ExitException) before surfacing as Timeout::Error. + publisher = Thread.new { Timeout.timeout(0.5) { holder[:context].publish } } + Timeout.timeout(5) { blocked.pop } + expect { publisher.join(5) }.to raise_error(Timeout::Error) + expect(holder[:context].finalized?).to be false + expect(holder[:context].pending_count).to eq(1) + Timeout.timeout(5) { holder[:context].publish } + expect(holder[:context].finalized?).to be true + expect(holder[:context].pending_count).to eq(0) + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::FINALIZE)).to eq(1) + end + + it "keeps a deferred finalize pending when its publishing thread is killed" do + config = ContextConfig.create + config.set_units(units) + holder = { goals: 0, events: [], calls: 0 } + blocked = Queue.new + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + holder[:events] << event + next unless event == ContextEventLogger::EVENT_TYPE::PUBLISH && holder[:goals] < 1 + + holder[:goals] += 1 + holder[:context].track("followup", nil) + holder[:context].finalize + end + end.new + handler = Object.new + handler.define_singleton_method(:publish) do |_context, _event| + holder[:calls] += 1 + if holder[:calls] == 2 + blocked << true + sleep + end + OpenStruct.new(success?: true) + end + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + + publisher = Thread.new { holder[:context].publish } + Timeout.timeout(5) { blocked.pop } + publisher.kill + publisher.join(5) + expect(holder[:context].finalized?).to be false + Timeout.timeout(5) { holder[:context].publish } + expect(holder[:context].finalized?).to be true + expect(holder[:context].pending_count).to eq(0) + end + + %i[timeout kill].each do |cancel| + it "keeps a deferred finalize pending when #{cancel} lands after it is claimed, before it starts" do + config = ContextConfig.create + config.set_units(units) + holder = { goals: 0, events: [] } + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + holder[:events] << event + next unless event == ContextEventLogger::EVENT_TYPE::PUBLISH && holder[:goals] < 1 + + holder[:goals] += 1 + holder[:context].track("followup", nil) + holder[:context].finalize + end + end.new + handler = Object.new + handler.define_singleton_method(:publish) { |_context, _event| OpenStruct.new(success?: true) } + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + + source = Context.instance_method(:flush).source_location.first + handoff = File.readlines(source).index { |line| line.strip == "claimed = nil if run_deferred_seal(claimed)" } + expect(handoff).not_to be_nil, "flush no longer has a run_deferred_seal(claimed) handoff line to park on" + handoff += 1 + parked = Queue.new + trace = TracePoint.new(:line) do |tp| + if tp.path == source && tp.lineno == handoff && Thread.current[:gate] + Thread.current[:gate] = false + parked << true + sleep + end + end + trace.enable + publisher = Thread.new do + Thread.current[:gate] = true + cancel == :timeout ? Timeout.timeout(5) { holder[:context].publish } : holder[:context].publish + rescue Timeout::Error + nil + end + begin + Timeout.timeout(5) { parked.pop } + cancel == :timeout ? publisher.raise(Timeout::Error) : publisher.kill + publisher.join(5) + ensure + trace.disable + publisher.join(1) || publisher.kill + end + + expect(holder[:context].finalized?).to be false + Timeout.timeout(5) { holder[:context].publish } + expect(holder[:context].finalized?).to be true + expect(holder[:context].pending_count).to eq(0) + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::FINALIZE)).to eq(1) + end + end + + # The interrupt lands the moment take_close_pending hands over the claim, + # before flush has recorded it; the claim must not be lost. + { "a successful publish" => true, "an empty publish" => false }.each do |label, queue_goal| + it "keeps a deferred finalize pending when a timeout lands as #{label} takes its claim" do + config = ContextConfig.create + config.set_units(units) + holder = { events: [] } + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) { |event, _data| holder[:events] << event } + end.new + handler = Object.new + handler.define_singleton_method(:publish) { |_context, _event| OpenStruct.new(success?: true) } + context = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + context.instance_variable_set(:@close_pending, ContextEventLogger::EVENT_TYPE::FINALIZE) + context.instance_variable_set(:@close_requests, 1) + context.track("goal1", nil) if queue_goal + taken = Queue.new + resume = Queue.new + allow(context).to receive(:take_close_pending).and_wrap_original do |original| + result = original.call + if Thread.current[:gate] && result + Thread.current[:gate] = false + taken << true + # The injected interrupt lands here unless the caller masked it. + resume.pop + end + result + end + publisher = Thread.new do + Thread.current[:gate] = true + context.publish + rescue Timeout::Error + nil + end + begin + Timeout.timeout(5) { taken.pop } + publisher.raise(Timeout::Error) + sleep 0.05 + resume << true + publisher.join(5) + ensure + resume << true + publisher.join(1) || publisher.kill + end + + expect(context.finalized?).to be(true).or(satisfy { context.instance_variable_get(:@close_pending) }) + Timeout.timeout(5) { context.publish } unless context.finalized? + expect(context.finalized?).to be true + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::FINALIZE)).to eq(1) + end + end + + it "reports cancellation at deferred handoff while another publisher's handler is blocked" do + config = ContextConfig.create + config.set_units(units) + holder = { calls: 0, requested: false } + handoff = Queue.new + second_send = Queue.new + release_send = Queue.new + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + if event == ContextEventLogger::EVENT_TYPE::PUBLISH && !holder[:requested] + holder[:requested] = true + holder[:context].track("followup", nil) + holder[:context].finalize + end + end + end.new + handler = Object.new + handler.define_singleton_method(:publish) do |_context, _event| + holder[:calls] += 1 + if holder[:calls] == 2 + second_send << true + release_send.pop + end + OpenStruct.new(success?: true) + end + context = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context] = context + allow(context).to receive(:run_deferred_seal).and_wrap_original do |original, claimed| + if Thread.current[:gate] + Thread.current[:gate] = false + handoff << true + sleep + end + original.call(claimed) + end + context.track("first", nil) + first = Thread.new do + Thread.current[:gate] = true + begin + Timeout.timeout(0.5) { context.publish } + rescue Timeout::Error + :timed_out + end + end + second = nil + begin + Timeout.timeout(5) { handoff.pop } + expect(context.instance_variable_get(:@close_pending)).to be false + second = Thread.new { context.publish } + Timeout.timeout(5) { second_send.pop } + expect(first.join(1)).not_to be_nil + expect(first.value).to eq(:timed_out) + expect(second.alive?).to be true + release_send << true + Timeout.timeout(5) { second.join } + context.publish unless context.finalized? + expect(context.finalized?).to be true + ensure + release_send << true + first.kill.join(1) + second&.kill&.join(1) + end + end + + it "balances finalizing state when cancellation lands during seal registration" do + context = create_ready_context + context.track("pending", nil) + source = Context.instance_method(:seal).source_location.first + target = File.readlines(source).index { |line| line.include?("@sealing += 1") } + 1 + parked = Queue.new + resume = Queue.new + trace = TracePoint.new(:line) do |tp| + if tp.path == source && tp.lineno == target + 1 && Thread.current[:gate] + Thread.current[:gate] = false + parked << true + resume.pop + end + end + trace.enable + worker = Thread.new do + Thread.current[:gate] = true + context.finalize + end + begin + Timeout.timeout(5) { parked.pop } + worker.kill + resume << true + worker.join(5) + ensure + trace.disable + resume << true + worker.join(1) || worker.kill + end + expect(context.closed?).to be false + expect(context.finalizing?).to be false + expect(context.pending_count).to eq(1) + end + + it "finishes seal-counter cleanup when interrupted waiting for the queue lock" do + context = create_ready_context + mutex = context.instance_variable_get(:@queue_mutex) + cleaning = Queue.new + resume = Queue.new + allow(mutex).to receive(:synchronize).and_wrap_original do |original, &block| + # The cleanup block is the only queue operation after the seal logger. + if Thread.current[:cleanup_gate] + Thread.current[:cleanup_gate] = false + cleaning << true + resume.pop + end + original.call(&block) + end + logger = Object.new + logger.define_singleton_method(:handle_event) do |event, _data| + Thread.current[:cleanup_gate] = true if event == ContextEventLogger::EVENT_TYPE::FINALIZE + end + context.instance_variable_set(:@event_logger, logger) + worker = Thread.new do + context.finalize + rescue Timeout::Error + nil + end + begin + Timeout.timeout(5) { cleaning.pop } + worker.raise(Timeout::Error) + sleep 0.05 + resume << true + worker.join(5) + ensure + resume << true + worker.join(1) || worker.kill + end + expect(context.instance_variable_get(:@sealing)).to eq(0) + end + + it "a close requested after another thread's rejected publish waits for a later success" do + config = ContextConfig.create + config.set_units(units) + holder = { events: [] } + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + holder[:events] << event + holder[:context].close if event == ContextEventLogger::EVENT_TYPE::ERROR && !holder[:asked] && (holder[:asked] = true) + end + end.new + calls = 0 + handler = instance_double(Absmartly::ContextPublisher) + allow(handler).to receive(:publish) do + calls += 1 + calls == 2 ? failure_future : publish_future + end + context = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context] = context + # Pause thread A just after its successful publish releases the publish + # lock, let thread B publish, be rejected and ask for close from the error + # callback, then resume A. A's earlier success must not carry B's request. + released = Queue.new + resume = Queue.new + pause_after_unlock = Class.new(Mutex) do + define_method(:synchronize) do |&block| + result = super(&block) + if Thread.current[:role] == :a && !Thread.current[:paused] + Thread.current[:paused] = true + released << true + resume.pop + end + result + end + end + context.instance_variable_set(:@publish_mutex, pause_after_unlock.new) + + context.track("goal_a", nil) + a = Thread.new do + Thread.current[:role] = :a + context.publish + end + Timeout.timeout(5) { released.pop } + context.track("goal_b", nil) + expect(Timeout.timeout(5) { context.publish }).to eq(failure_future) + resume << true + Timeout.timeout(5) { a.join } + + expect(context.closed?).to be false + expect(context.pending_count).to eq(1) + Timeout.timeout(5) { context.publish } + expect(context.closed?).to be true + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::CLOSE)).to eq(1) + end + + it "a close requested from a publish callback during close is carried out by the next publish once close raises" do + config = ContextConfig.create + config.set_units(units) + holder = { goals: 0 } + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + next unless event == ContextEventLogger::EVENT_TYPE::PUBLISH && holder[:goals] < 2 + + holder[:goals] += 1 + holder[:context].track("cb#{holder[:goals]}", nil) + holder[:context].close + end + end.new + handler = instance_double(Absmartly::ContextPublisher) + allow(handler).to receive(:publish).and_return(nil) + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + + expect { Timeout.timeout(5) { holder[:context].close } }.to raise_error(StandardError, /retry close/) + Timeout.timeout(5) { holder[:context].publish } + expect(holder[:context].closed?).to be true + expect(holder[:context].pending_count).to eq(0) + end + + it "keeps a close another thread requests while finalize waits for the publish lock" do + config = ContextConfig.create + config.set_units(units) + holder = { events: [] } + in_publish = Queue.new + release = Queue.new + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + holder[:events] << event + if event == ContextEventLogger::EVENT_TYPE::ERROR && !holder[:asked] + holder[:asked] = true + holder[:context].close + end + holder[:context].track("cb", nil) if event == ContextEventLogger::EVENT_TYPE::PUBLISH && holder[:produce] + end + end.new + calls = 0 + handler = instance_double(Absmartly::ContextPublisher) + allow(handler).to receive(:publish) do + calls += 1 + if calls == 1 + in_publish << true + release.pop + next failure_future + end + publish_future + end + context = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context] = context + context.track("goal_a", nil) + # Thread A holds the publish lock; B starts finalize and waits for it. A's + # publish is rejected and its error callback asks for close. B then hits + # the pass bound and raises the retry error; A's request must survive. + a = Thread.new { context.publish } + Timeout.timeout(5) { in_publish.pop } + holder[:produce] = true + b = Thread.new do + context.finalize + rescue StandardError => e + e + end + Timeout.timeout(5) { sleep 0.05 until b.status == "sleep" } + release << true + Timeout.timeout(5) { a.join } + expect(Timeout.timeout(5) { b.value }).to be_a(StandardError) + holder[:produce] = false + + Timeout.timeout(5) { context.publish } + expect(context.closed?).to be true + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::CLOSE)).to eq(1) + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::FINALIZE)).to eq(0) + end + + it "matches the system entry's name exactly, not case-insensitively" do + seen = nil + matcher = Class.new do + define_method(:evaluate) do |_audience, attributes| + seen = attributes + Struct.new(:result).new(true) + end + end.new + config = ContextConfig.create + config.set_units(units) + context = Context.create(clock, config, audience_strict_data_future_ready, data_provider, event_handler, + event_logger, variable_parser, matcher, application: "website", environment: "prod") + context.set_attribute("Environment", "staging") + context.peek_treatment("exp_test_ab") + + expect(seen).to eq("application" => "website", "environment" => "prod", "Environment" => "staging") + end + + it "a close requested from the error callback of a rejected finalize seals on the next good publish" do + config = ContextConfig.create + config.set_units(units) + holder = { events: [] } + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + holder[:events] << event + holder[:context].close if event == ContextEventLogger::EVENT_TYPE::ERROR && !holder[:asked] && (holder[:asked] = true) + end + end.new + responses = [failure_future, publish_future] + handler = instance_double(Absmartly::ContextPublisher) + allow(handler).to receive(:publish) { responses.shift } + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + + expect { Timeout.timeout(5) { holder[:context].finalize } }.to raise_error(Exception, "FAILED") + expect(holder[:context].closed?).to be false + Timeout.timeout(5) { holder[:context].publish } + expect(holder[:context].closed?).to be true + expect(holder[:context].pending_count).to eq(0) + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::CLOSE)).to eq(1) + end + + it "builds the attribute map with two allocations per call for String names" do + config = ContextConfig.create + config.set_units(units) + context = Context.create(clock, config, data_future_ready, data_provider, event_handler, event_logger, + variable_parser, audience_matcher, application: "website", environment: "prod") + 10.times { |i| context.set_attribute("a#{i}", i) } + context.send(:attributes_map) + before = GC.stat(:total_allocated_objects) + 1000.times { context.send(:attributes_map) } + expect(GC.stat(:total_allocated_objects) - before).to be < 2100 + end + + it "keeps a close carried from a rejected publish when a later finalize hits the pass bound" do + config = ContextConfig.create + config.set_units(units) + holder = { produce: false } + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + (holder[:events] ||= []) << event + holder[:context].close if event == ContextEventLogger::EVENT_TYPE::ERROR && !holder[:asked] && (holder[:asked] = true) + holder[:context].track("cb", nil) if event == ContextEventLogger::EVENT_TYPE::PUBLISH && holder[:produce] + end + end.new + responses = [failure_future] + handler = instance_double(Absmartly::ContextPublisher) + allow(handler).to receive(:publish) { responses.shift || publish_future } + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + Timeout.timeout(5) { holder[:context].publish } + holder[:produce] = true + expect { Timeout.timeout(5) { holder[:context].finalize } }.to raise_error(StandardError, /retry close/) + holder[:produce] = false + Timeout.timeout(5) { holder[:context].publish } + expect(holder[:context].closed?).to be true + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::CLOSE)).to eq(1) + end + + + it "keeps a carried close when an explicit finalize is rejected" do + config = ContextConfig.create + config.set_units(units) + holder = { events: [] } + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + holder[:events] << event + holder[:context].close if event == ContextEventLogger::EVENT_TYPE::ERROR && !holder[:asked] && (holder[:asked] = true) + end + end.new + responses = [failure_future, failure_future] + handler = instance_double(Absmartly::ContextPublisher) + allow(handler).to receive(:publish) { responses.shift || publish_future } + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + Timeout.timeout(5) { holder[:context].publish } + expect { Timeout.timeout(5) { holder[:context].finalize } }.to raise_error(Exception, "FAILED") + Timeout.timeout(5) { holder[:context].publish } + expect(holder[:context].closed?).to be true + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::CLOSE)).to eq(1) + end + + + it "keeps a close requested from a publish callback when finalize's retry pass is rejected" do + config = ContextConfig.create + config.set_units(units) + holder = { events: [] } + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + holder[:events] << event + next unless event == ContextEventLogger::EVENT_TYPE::PUBLISH && !holder[:asked] + + holder[:asked] = true + holder[:context].track("cb", nil) + holder[:context].close + end + end.new + responses = [publish_future, failure_future] + handler = instance_double(Absmartly::ContextPublisher) + allow(handler).to receive(:publish) { responses.shift || publish_future } + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + expect { Timeout.timeout(5) { holder[:context].finalize } }.to raise_error(Exception, "FAILED") + Timeout.timeout(5) { holder[:context].publish } + expect(holder[:context].closed?).to be true + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::CLOSE)).to eq(1) + end + + + it "carries the latest request when a callback asks for finalize then close" do + config = ContextConfig.create + config.set_units(units) + holder = { events: [] } + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + holder[:events] << event + next unless event == ContextEventLogger::EVENT_TYPE::ERROR && !holder[:asked] + + holder[:asked] = true + holder[:context].finalize + holder[:context].close + end + end.new + responses = [failure_future] + handler = instance_double(Absmartly::ContextPublisher) + allow(handler).to receive(:publish) { responses.shift || publish_future } + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + + Timeout.timeout(5) { holder[:context].publish } + Timeout.timeout(5) { holder[:context].publish } + expect(holder[:context].closed?).to be true + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::CLOSE)).to eq(1) + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::FINALIZE)).to eq(0) + end + + it "a close requested while a deferred finalize fails replaces that finalize" do + config = ContextConfig.create + config.set_units(units) + holder = { events: [], stage: 0 } + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + holder[:events] << event + if event == ContextEventLogger::EVENT_TYPE::PUBLISH && holder[:stage].zero? + holder[:stage] = 1 + holder[:context].track("cb", nil) + holder[:context].finalize + elsif event == ContextEventLogger::EVENT_TYPE::ERROR && holder[:stage] == 1 + holder[:stage] = 2 + holder[:context].close + end + end + end.new + # Publish 1 succeeds and its callback defers finalize; that finalize's own + # publish is rejected and its error callback asks for close. + responses = [publish_future, failure_future] + handler = instance_double(Absmartly::ContextPublisher) + allow(handler).to receive(:publish) { responses.shift || publish_future } + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + + expect { Timeout.timeout(5) { holder[:context].publish } }.to raise_error(Exception, "FAILED") + Timeout.timeout(5) { holder[:context].publish } + expect(holder[:context].closed?).to be true + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::CLOSE)).to eq(1) + expect(holder[:events].count(ContextEventLogger::EVENT_TYPE::FINALIZE)).to eq(0) + end + + describe "overlapping seals and publishes" do + # Every gate an example opens and every worker it starts, so a failing + # assertion can't leave a worker blocked on a gate after the example. + def gate + (@gates ||= []) << Queue.new + @gates.last + end + + def worker(role = nil, &block) + thread = Thread.new do + Thread.current[:role] = role + block.call + end + (@workers ||= []) << thread + thread + end + + after do + Array(@gates).each { |q| 3.times { q << true } } + stuck = Array(@workers).reject do |t| + t.join(5) || (t.kill && t.join(5)) + end + raise "#{stuck.size} worker thread(s) did not exit" unless stuck.empty? + end + + def overlap_context(responses, logger) + config = ContextConfig.create + config.set_units(units) + @sent = [] + handler = Object.new + sent = @sent + handler.define_singleton_method(:publish) do |_context, event| + step = responses.shift + step = step.call if step.respond_to?(:call) + sent << [step.equal?(:ok) ? :ok : :rejected, (event.goals || []).map(&:name)] + step.equal?(:ok) ? OpenStruct.new(success?: true) : OpenStruct.new(exception: Exception.new("FAILED"), success?: false) + end + Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + end + + def recording_logger(events, &block) + Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, data| + events << event + block&.call(event, data) + end + end.new + end + + # Pauses the calling thread after its seal's flush returns (before the seal + # decides what to do with the result) until released. + def pause_seal_after_flush(context, role, paused, release) + original = context.method(:flush) + allow(context).to receive(:flush) do |**kwargs| + result = original.call(**kwargs) + if kwargs[:sealing] && Thread.current[:role] == role && !Thread.current[:paused] + Thread.current[:paused] = true + paused << true + release.pop + end + result + end + end + + it "close drops only the rejected batch, not goals tracked while it was in flight" do + events = [] + in_flight = gate + release = gate + responses = [-> { in_flight << true; release.pop; :rejected }, :ok] + context = overlap_context(responses, recording_logger(events)) + context.track("initial", nil) + + closer = worker { context.close } + Timeout.timeout(5) { in_flight.pop } + context.track("never_sent", nil) + release << true + Timeout.timeout(5) { closer.join } + + expect(@sent).to eq([[:rejected, ["initial"]], [:ok, ["never_sent"]]]) + expect(context.closed?).to be true + expect(context.pending_count).to eq(0) + expect(events.count(ContextEventLogger::EVENT_TYPE::CLOSE)).to eq(1) + end + + it "an independent publish hands off a close requested by a finalize that is still failing" do + events = [] + holder = {} + logger = recording_logger(events) do |event, _data| + if event == ContextEventLogger::EVENT_TYPE::ERROR && !holder[:asked] + holder[:asked] = true + holder[:context].close + end + end + context = overlap_context([:rejected, :ok], logger) + holder[:context] = context + paused = gate + release = gate + pause_seal_after_flush(context, :a, paused, release) + context.track("goal1", nil) + + a = worker(:a) do + context.finalize + rescue Exception => e # rubocop:disable Lint/RescueException + e + end + Timeout.timeout(5) { paused.pop } + Timeout.timeout(5) { context.publish } + expect(context.closed?).to be true + release << true + expect(Timeout.timeout(5) { a.value }.message).to eq("FAILED") + + expect(@sent).to eq([[:rejected, ["goal1"]], [:ok, ["goal1"]]]) + expect(events.count(ContextEventLogger::EVENT_TYPE::CLOSE)).to eq(1) + expect(events.count(ContextEventLogger::EVENT_TYPE::FINALIZE)).to eq(0) + end + + it "an empty publish hands off a close left pending after the queue was delivered" do + events = [] + holder = {} + logger = recording_logger(events) do |event, _data| + if event == ContextEventLogger::EVENT_TYPE::ERROR && !holder[:asked] + holder[:asked] = true + holder[:context].close + end + end + context = overlap_context([:rejected, :ok, :ok], logger) + holder[:context] = context + paused = gate + release = gate + pause_seal_after_flush(context, :a, paused, release) + context.track("goal1", nil) + + # finalize is rejected and its error callback asks for close; while that + # finalize is still unwinding, another publish delivers the queue, so + # the close it hands off has nothing left to send. + a = worker(:a) do + context.finalize + rescue Exception => e # rubocop:disable Lint/RescueException + e + end + Timeout.timeout(5) { paused.pop } + allow(context).to receive(:take_close_pending).and_return(nil) + Timeout.timeout(5) { context.publish } + allow(context).to receive(:take_close_pending).and_call_original + release << true + Timeout.timeout(5) { a.join } + expect(context.pending_count).to eq(0) + expect(context.closed?).to be false + + Timeout.timeout(5) { context.publish } + expect(context.closed?).to be true + expect(events.count(ContextEventLogger::EVENT_TYPE::CLOSE)).to eq(1) + end + + it "reports finalizing? only while a seal is running, across overlapping seals" do + context = overlap_context([:ok], recording_logger([])) + paused = gate + release = gate + pause_seal_after_flush(context, :a, paused, release) + context.track("goal1", nil) + expect(context.finalizing?).to be false + + a = worker(:a) do + context.finalize + end + Timeout.timeout(5) { paused.pop } + expect(context.finalizing?).to be true + release << true + Timeout.timeout(5) { a.join } + expect(context.finalizing?).to be false + expect(context.finalized?).to be true + end + + + it "stays finalizing? while a second seal runs after the first one raised" do + first = gate + second = gate + calls = 0 + config = ContextConfig.create + config.set_units(units) + handler = Object.new + handler.define_singleton_method(:publish) do |_c, _e| + calls += 1 + if calls == 1 + first.pop + next OpenStruct.new(exception: Exception.new("FAILED"), success?: false) + end + second.pop + OpenStruct.new(success?: true) + end + context = Context.create(clock, config, data_future_ready, data_provider, handler, nil, + variable_parser, audience_matcher) + context.track("goal1", nil) + entered = gate + original = context.method(:flush) + allow(context).to receive(:flush) do |**kwargs| + entered << Thread.current[:role] if kwargs[:sealing] + original.call(**kwargs) + end + a = worker(:a) do + context.finalize + rescue Exception => e # rubocop:disable Lint/RescueException + e + end + Timeout.timeout(5) { entered.pop } + b = worker(:b) do + context.finalize + end + Timeout.timeout(5) { entered.pop } + Timeout.timeout(5) { sleep 0.01 until b.status == "sleep" } + first << true + expect(Timeout.timeout(5) { a.value }.message).to eq("FAILED") + expect(context.finalizing?).to be true + second << true + Timeout.timeout(5) { b.join } + expect(context.finalizing?).to be false + expect(context.finalized?).to be true + end + + it "a seal's own empty pass leaves a pending close for a later publish" do + events = [] + holder = {} + logger = recording_logger(events) do |event, _data| + if event == ContextEventLogger::EVENT_TYPE::ERROR && !holder[:asked] + holder[:asked] = true + holder[:context].close + end + end + context = overlap_context([:rejected, :ok], logger) + holder[:context] = context + context.track("goal1", nil) + + # A publish is rejected and its error callback asks for close. The queue + # is then delivered without handing the close off, so it stays pending. + Timeout.timeout(5) { context.publish } + allow(context).to receive(:take_close_pending).and_return(nil) + Timeout.timeout(5) { context.publish } + allow(context).to receive(:take_close_pending).and_call_original + expect(context.pending_count).to eq(0) + expect(context.instance_variable_get(:@close_pending)).to eq(ContextEventLogger::EVENT_TYPE::CLOSE) + + # A seal's own empty pass, paused before it decides: it must neither + # claim nor drop the pending close, which the publish below still sees. + paused = gate + release = gate + pause_seal_after_flush(context, :a, paused, release) + a = worker(:a) do + context.finalize + end + begin + Timeout.timeout(5) { paused.pop } + expect(context.instance_variable_get(:@close_pending)).to eq(ContextEventLogger::EVENT_TYPE::CLOSE) + Timeout.timeout(5) { context.publish } + expect(context.closed?).to be true + expect(context.instance_variable_get(:@sealed_by)).to eq(ContextEventLogger::EVENT_TYPE::CLOSE) + ensure + release << true + a.join(5) || a.kill + end + expect(events.select { |e| [ContextEventLogger::EVENT_TYPE::CLOSE, ContextEventLogger::EVENT_TYPE::FINALIZE].include?(e) }) + .to eq([ContextEventLogger::EVENT_TYPE::CLOSE]) + end + + it "a failed older deferred finalize does not override a newer close already handed off" do + events = [] + holder = {} + logger = recording_logger(events) do |event, _data| + next unless event == ContextEventLogger::EVENT_TYPE::PUBLISH + + holder[:publishes] = (holder[:publishes] || 0) + 1 + if holder[:publishes] == 1 + holder[:context].track("cb1", nil) + holder[:context].finalize + elsif Thread.current[:role] == :b + holder[:context].close + end + end + # Publish 1 (thread A) succeeds and defers finalize. That finalize's own + # publish is rejected; before it re-arms itself, thread B publishes + # successfully, asks for close and claims it. A's failure must not then + # restore the older finalize, which an empty publish would carry out + # before B's newer close. + context = overlap_context([:ok, :rejected, :ok, :ok], logger) + holder[:context] = context + paused = gate + release = gate + claimed = gate + resume_b = gate + original_seal = context.method(:seal) + allow(context).to receive(:seal) do |event_type| + original_seal.call(event_type) + rescue Exception # rubocop:disable Lint/RescueException + if Thread.current[:role] == :a && !Thread.current[:paused] + Thread.current[:paused] = true + paused << true + release.pop + end + raise + end + original_run = context.method(:run_deferred_seal) + allow(context).to receive(:run_deferred_seal) do |claim| + if Thread.current[:role] == :b && !Thread.current[:paused] + Thread.current[:paused] = true + claimed << true + resume_b.pop + end + original_run.call(claim) + end + context.track("goal1", nil) + + a = worker(:a) do + context.publish + rescue Exception => e # rubocop:disable Lint/RescueException + e + end + b = nil + begin + Timeout.timeout(5) { paused.pop } + context.track("goal_b", nil) + b = worker(:b) do + context.publish + end + Timeout.timeout(5) { claimed.pop } + release << true + expect(Timeout.timeout(5) { a.value }.message).to eq("FAILED") + # An empty publish before B carries out its claimed close: it must not + # find A's older finalize restored and seal with it. + Timeout.timeout(5) { context.publish } + resume_b << true + Timeout.timeout(5) { b.join } + ensure + release << true + resume_b << true + [a, b].compact.each { |t| t.join(5) || t.kill } + end + + expect(context.closed?).to be true + expect(events.count(ContextEventLogger::EVENT_TYPE::CLOSE)).to eq(1) + expect(events.count(ContextEventLogger::EVENT_TYPE::FINALIZE)).to eq(0) + end + + it "a second finalize is not turned into a close by a failing first one" do + events = [] + holder = {} + logger = recording_logger(events) do |event, _data| + next unless event == ContextEventLogger::EVENT_TYPE::PUBLISH && !holder[:asked] + + holder[:asked] = true + holder[:context].track("followup", nil) + holder[:context].close + end + context = overlap_context([:rejected, :ok, :rejected], logger) + holder[:context] = context + paused = gate + release = gate + pause_seal_after_flush(context, :a, paused, release) + context.track("goal1", nil) + + a = worker(:a) do + context.finalize + rescue Exception => e # rubocop:disable Lint/RescueException + e + end + Timeout.timeout(5) { paused.pop } + expect { Timeout.timeout(5) { context.finalize } }.to raise_error(Exception, "FAILED") + release << true + expect(Timeout.timeout(5) { a.value }.message).to eq("FAILED") + + expect(context.closed?).to be false + expect(context.pending_count).to eq(1) + expect(@sent.last).to eq([:rejected, ["followup"]]) + expect(events.count(ContextEventLogger::EVENT_TYPE::CLOSE)).to eq(0) + end + end + + it "a deferred close still raises a publisher error from its own publish" do + config = ContextConfig.create + config.set_units(units) + holder = {} + calls = 0 + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) do |event, _data| + next unless event == ContextEventLogger::EVENT_TYPE::PUBLISH && !holder[:done] + + holder[:done] = true + holder[:context].track("again", nil) + holder[:context].close + end + end.new + handler = instance_double(Absmartly::ContextPublisher) + allow(handler).to receive(:publish) do + calls += 1 + raise IOError, "collector down" if calls > 1 + + nil + end + holder[:context] = Context.create(clock, config, data_future_ready, data_provider, handler, logger, + variable_parser, audience_matcher) + holder[:context].track("goal1", nil) + + expect { Timeout.timeout(5) { holder[:context].publish } }.to raise_error(IOError, "collector down") + expect(holder[:context].closed?).to be false + expect(holder[:context].pending_count).to eq(1) + end + + it "does not let an overridden public getter change matcher attributes" do + seen = [] + matcher = Class.new do + define_method(:evaluate) do |_audience, attributes| + seen << attributes.dup + Struct.new(:result).new(true) + end + end.new + config = ContextConfig.create + config.set_unit(:session_id, "alice") + config.set_attribute(:country, "US") + context = Context.create(clock, config, data_future_ready, data_provider, event_handler, + event_logger, variable_parser, matcher) + context.define_singleton_method(:get_attributes) { { bad: "override" } } + context.experiments.each { |name| context.peek_treatment(name) } + + expect(seen).not_to be_empty + expect(seen).to all(include(country: "US")) + expect(seen.any? { |attributes| attributes.key?(:bad) }).to be false + end + + it "set_unit returns the stored UID, as in v1.3.0" do + context = create_ready_context + expect(context.set_unit("extra_id", " padded ")).to eq("padded") + expect(context.set_unit("num_id", 42)).to eq("42") + expect(context.set_unit("num_id", "42")).to eq("42") + expect(context.set_unit(:extra_id, "padded")).to eq("padded") + end + + it "skips revalidation on warmed reads of an experiment with no rules or audience" do + context = create_ready_context + context.treatment("exp_test_ab") + context.set_attribute("age", 30) + calls = 0 + allow(context).to receive(:attributes_map).and_wrap_original { |m| calls += 1; m.call } + allow(context).to receive(:audience_matches).and_wrap_original { |m, *args| calls += 1; m.call(*args) } + + 5.times { context.treatment("exp_test_ab") && context.peek_treatment("exp_test_ab") } + expect(calls).to eq(0) + end + + it "accepts the same unit again as a String or a number, as in v1.3.0" do + context = create_ready_context + context.set_unit("db_id", 123456) + expect { context.set_unit("db_id", "123456") }.not_to raise_error + expect { context.set_unit(:db_id, " 123456 ") }.not_to raise_error + expect(context.get_unit(:db_id)).to eq(123456) + expect { context.set_unit("db_id", "654321") }.to raise_error(IllegalStateException, "Unit 'db_id' already set.") + end + it "set unit throws on already set" do context = create_ready_context @@ -455,6 +2188,17 @@ def to_s expect(context.pending_count).to eq(2 + overrides.size * 2) end + it "returns control once the override of an unknown experiment is cleared" do + context = create_ready_context + context.set_override("exp_test_new", 3) + expect(context.treatment("exp_test_new")).to eq(3) + + context.set_override("exp_test_new", nil) + expect(context.treatment("exp_test_new")).to eq(0) + expect(context.treatment("exp_test_new")).to eq(0) + expect(context.pending_count).to eq(2) + end + it "set override before ready" do context = create_context(data_future) expect(context.ready?).to be_falsey @@ -730,33 +2474,15 @@ def to_s expect(event_handler).to have_received(:publish).with(context, expected).once end - it "getVariableValueQueuesExposureWithAudienceMismatchFalseAndControlVariantOnAudienceMismatchInStrictMode" do + # As java-sdk: a strict audience mismatch leaves the unit unassigned, so the + # read gives the default and exposes nothing; treatment still exposes it. + it "getVariableValueDoesNotQueueExposureOnAudienceMismatchInStrictMode" do context = create_context(audience_strict_data_future_ready) expect(context.variable_value("banner.size", "small")).to eq("small") + expect(context.pending_count).to eq(0) + expect(context.treatment("exp_test_ab")).to eq(0) expect(context.pending_count).to eq(1) - - publish_future = nil - allow(event_handler).to receive(:publish).and_return(publish_future) - - context.publish - - expected = PublishEvent.new - expected.hashed = true - expected.published_at = clock_in_millis - expected.units = publish_units - - expected.exposures = [ - Exposure.new(1, "exp_test_ab", "session_id", 0, clock_in_millis, false, true, false, false, false, - true) - ] - - allow(event_handler).to receive(:publish).and_return(publish_future) - - context.publish - - expect(event_handler).to have_received(:publish).once - expect(event_handler).to have_received(:publish).with(context, expected).once end it "getVariableValueCallsEventLogger" do @@ -829,12 +2555,16 @@ def to_s expect(context.custom_field_value("exp_test_no_custom_fields", "languages")).to be_nil end - it "reads a custom field with a missing or null type as untyped text" do + def untyped_custom_fields_payload raw = JSON.parse(json) fields = raw["experiments"].find { |e| e["name"] == "exp_test_ab" }["customFieldValues"] fields << { "name" => "untyped", "value" => "x" } << { "name" => "null_type", "value" => "y", "type" => nil } payload = JSON.generate(raw) - context = create_context(client_mock(descr.deserialize(payload, 0, payload.length)).context_data) + descr.deserialize(payload, 0, payload.length) + end + + it "reads a custom field with a missing or null type as untyped text" do + context = create_context(client_mock(untyped_custom_fields_payload).context_data) expect(context.ready?).to be true expect(context.failed?).to be false @@ -845,14 +2575,10 @@ def to_s end it "reads a custom field with a missing or null type as untyped text after a refresh" do - raw = JSON.parse(json) - fields = raw["experiments"].find { |e| e["name"] == "exp_test_ab" }["customFieldValues"] - fields << { "name" => "untyped", "value" => "x" } << { "name" => "null_type", "value" => "y", "type" => nil } - payload = JSON.generate(raw) - untyped_provider = DefaultContextDataProvider.new(client_mock(descr.deserialize(payload, 0, payload.length))) + untyped_provider = DefaultContextDataProvider.new(client_mock(untyped_custom_fields_payload)) context = create_context(data_future_ready, dt_provider: untyped_provider) - expect(context.refresh).to be_nil + expect { context.refresh }.not_to raise_error expect(context.failed?).to be false expect(context.custom_field_value("exp_test_ab", "untyped")).to eq("x") expect(context.custom_field_type("exp_test_ab", "untyped")).to be_nil @@ -1302,6 +3028,44 @@ def to_unsafe_h expect(context.pending_count).to eq(3) end + describe "a handler that mutates the payload it accepted" do + def mutating_handler(sent, response, during_first: nil) + handler = Object.new + handler.define_singleton_method(:publish) do |context, event| + sent << [(event.goals || []).map(&:name), (event.exposures || []).map(&:name)] + during_first&.call(context) if sent.size == 1 + event.goals&.clear + event.exposures&.clear + response + end + handler + end + + it "does not leave accepted events queued or send them again" do + sent = [] + context = create_ready_context(evt_handler: mutating_handler(sent, OpenStruct.new(success?: true))) + context.track("order", nil) + context.treatment("exp_test_ab") + context.publish + + expect(context.pending_count).to eq(0) + context.publish + expect(sent).to eq([[["order"], ["exp_test_ab"]]]) + end + + it "close still drops only the rejected batch it sent" do + sent = [] + queue_later = ->(context) { context.track("queued_meanwhile", nil) } + context = create_ready_context(evt_handler: mutating_handler(sent, OpenStruct.new(success?: false), + during_first: queue_later)) + context.track("order", nil) + context.close + + expect(sent).to eq([[["order"], []], [["queued_meanwhile"], []]]) + expect(context.pending_count).to eq(0) + end + end + it "publish does not call event handler when queue is empty" do context = create_ready_context expect(context.pending_count).to eq(0) @@ -1385,7 +3149,7 @@ def to_unsafe_h end it "publishExceptionally" do - ev = instance_double(ContextPublisher) + ev = instance_double(Absmartly::ContextPublisher) context = create_ready_context(evt_handler: ev) expect(context.ready?).to be_truthy expect(context.failed?).to be_falsey @@ -1493,7 +3257,7 @@ def to_unsafe_h allow(data_provider).to receive(:context_data).and_return(failure_future) - expect(context.refresh).to eq(failure) + context.refresh # A failed refresh keeps the current data; only the initial fetch fails a context. expect(context.failed?).to be_falsey @@ -1557,7 +3321,7 @@ def to_unsafe_h describe "error recovery and resilience" do it "context remains usable after failed publish" do - ev = instance_double(ContextPublisher) + ev = instance_double(Absmartly::ContextPublisher) allow(ev).to receive(:publish).and_return(failure_future) context = create_ready_context(evt_handler: ev) @@ -1572,7 +3336,7 @@ def to_unsafe_h end it "queues new events after failed publish" do - ev = instance_double(ContextPublisher) + ev = instance_double(Absmartly::ContextPublisher) allow(ev).to receive(:publish).and_return(failure_future) context = create_ready_context(evt_handler: ev) @@ -1603,7 +3367,7 @@ def to_unsafe_h http_client = instance_double(DefaultHttpClient) allow(http_client).to receive(:put) .and_return(DefaultHttpClient.default_response(500, "Internal Server Error", nil, nil)) - publisher = DefaultContextPublisher.new(Client.new(client_config, http_client)) + publisher = Absmartly::DefaultContextPublisher.new(Client.new(client_config, http_client)) context = create_ready_context(evt_handler: publisher) context.track("goal1", nil) @@ -2082,7 +3846,7 @@ def create_refreshable_context(modified) end it "should not clear queue on failure" do - ev = instance_double(ContextPublisher) + ev = instance_double(Absmartly::ContextPublisher) allow(ev).to receive(:publish).and_return(failure_future) context = create_ready_context(evt_handler: ev) @@ -2128,26 +3892,70 @@ def create_refreshable_context(modified) expect { context.publish }.to raise_error(IllegalStateException) end - it "raises the publish failure, stays open with events queued, and a second close seals" do - ev = instance_double(ContextPublisher) + it "close logs a rejected final publish and seals, as in v1.3.0" do + ev = instance_double(Absmartly::ContextPublisher) allow(ev).to receive(:publish).and_return(failure_future) context = create_ready_context(evt_handler: ev) context.track("goal1", nil) expect(context.pending_count).to eq(1) - expect { context.close }.to raise_error(Exception, "FAILED") + expect { context.close }.not_to raise_error + expect(context.closed?).to be true + expect(context.pending_count).to eq(0) + expect(ev).to have_received(:publish).once + expect(event_logger).to have_received(:handle_event).with(ContextEventLogger::EVENT_TYPE::ERROR, "FAILED").once + expect(event_logger).to have_received(:handle_event).with(ContextEventLogger::EVENT_TYPE::CLOSE, nil).once + end + + it "close re-raises a publisher that raises and stays open with the events queued" do + ev = instance_double(Absmartly::ContextPublisher) + allow(ev).to receive(:publish).and_raise(StandardError, "boom") + context = create_ready_context(evt_handler: ev) + context.track("goal1", nil) + + expect { context.close }.to raise_error(StandardError, "boom") + expect(context.closed?).to be false + expect(context.pending_count).to eq(1) + + allow(ev).to receive(:publish).and_return(nil) + expect { context.close }.not_to raise_error + expect(context.closed?).to be true + expect(context.pending_count).to eq(0) + end + + it "finalize raises a rejected final publish, stays open with events queued, and a second finalize seals" do + ev = instance_double(Absmartly::ContextPublisher) + allow(ev).to receive(:publish).and_return(failure_future) + context = create_ready_context(evt_handler: ev) + context.track("goal1", nil) + + expect { context.finalize }.to raise_error(Exception, "FAILED") expect(context.closed?).to be false expect(context.pending_count).to eq(1) allow(ev).to receive(:publish).and_return(nil) - expect(context.close).to be_nil + expect(context.finalize).to be_nil expect(context.closed?).to be true expect(context.pending_count).to eq(0) expect(ev).to have_received(:publish).twice end + it "finalize keeps a StandardError instance and wraps a bare Exception with its cause" do + [StandardError.new("rejected"), Exception.new("rejected")].each do |failure| + ev = instance_double(Absmartly::ContextPublisher) + allow(ev).to receive(:publish).and_return(failure) + context = create_ready_context(evt_handler: ev) + context.track("goal1", nil) + expect { context.finalize }.to raise_error(StandardError, "rejected") do |error| + expect(failure.is_a?(StandardError) ? error : error.cause).to equal(failure) + end + expect(context.closed?).to be false + expect(context.pending_count).to eq(1) + end + end + it "finalize raises the publish failure and leaves the context open" do - ev = instance_double(ContextPublisher) + ev = instance_double(Absmartly::ContextPublisher) allow(ev).to receive(:publish).and_return(failure_future) context = create_ready_context(evt_handler: ev) context.track("goal1", nil) @@ -2291,7 +4099,7 @@ def create_refreshable_context(modified) end it "should call event logger on close error" do - ev = instance_double(ContextPublisher) + ev = instance_double(Absmartly::ContextPublisher) allow(ev).to receive(:publish).and_return(failure_future) event_logger.clear @@ -2299,7 +4107,7 @@ def create_refreshable_context(modified) event_logger.clear context.track("goal1", nil) - expect { context.close }.to raise_error(Exception, "FAILED") + expect { context.close }.not_to raise_error expect(event_logger).to have_received(:handle_event).with( ContextEventLogger::EVENT_TYPE::ERROR, "FAILED" @@ -2307,7 +4115,7 @@ def create_refreshable_context(modified) expect(event_logger).not_to have_received(:handle_event).with( ContextEventLogger::EVENT_TYPE::PUBLISH, anything ) - expect(context.closed?).to be false + expect(context.closed?).to be true end end @@ -2318,6 +4126,22 @@ def create_refreshable_context(modified) expect(context.custom_field_type("exp_test_ab", "country")).to eq("string") expect(context.custom_field_type("exp_test_ab", "overrides")).to eq("json") end + + it "reads a custom field with a missing or null type as text instead of failing the context" do + raw = { experiments: [{ id: 1, name: "exp_types", unitType: "session_id", iteration: 1, seedHi: 1, seedLo: 2, + split: [0.5, 0.5], trafficSeedHi: 3, trafficSeedLo: 4, trafficSplit: [0, 1], + fullOnVariant: 0, variants: [{ name: "A", config: nil }, { name: "B", config: nil }], + customFieldValues: [{ name: "missing", value: "x" }, { name: "null", value: "1", type: nil }, + { name: "number", value: "7", type: "number" }] }] }.to_json + parsed = DefaultContextDataDeserializer.new.deserialize(raw, 0, raw.size) + context = create_context(OpenStruct.new(data_future: parsed, success?: true)) + + expect(context.ready?).to be true + expect(context.custom_field_value("exp_types", "missing")).to eq("x") + expect(context.custom_field_type("exp_types", "missing")).to be_nil + expect(context.custom_field_value("exp_types", "null")).to eq("1") + expect(context.custom_field_value("exp_types", "number")).to eq(7) + end end describe "get_unit" do diff --git a/spec/create_context_async_spec.rb b/spec/create_context_async_spec.rb index 7b75a5fd..809dd873 100644 --- a/spec/create_context_async_spec.rb +++ b/spec/create_context_async_spec.rb @@ -13,7 +13,9 @@ require "context_event_logger" require "audience_matcher" require "json/unit" +require "json" require "logger" +require "timeout" RSpec.describe "create_context_async" do let(:units) { @@ -31,7 +33,7 @@ let(:publish_future) { OpenStruct.new(success?: true) } let(:event_handler) do - ev = instance_double(ContextPublisher) + ev = instance_double(Absmartly::ContextPublisher) allow(ev).to receive(:publish).and_return(publish_future) ev end @@ -40,6 +42,15 @@ let(:audience_matcher) { AudienceMatcher.new(DefaultAudienceDeserializer.new) } let(:failure) { Exception.new("FAILED") } + # A read still holding a snapshot a refresh has since replaced: resolved + # against that snapshot under the assignment lock, as a read that captured + # it before the refresh would be. + def stale_read(context, name, state) + context.instance_variable_get(:@assignment_mutex).synchronize do + context.send(:cached_or_new_assignment, name, state) + end + end + def slow_client_mock(delay: 0.1) client = instance_double(Client) allow(client).to receive(:context_data) do @@ -213,6 +224,1994 @@ def failed_client_mock expect(context.failed?).to be true end + + it "keeps data a refresh installed when the initial fetch then fails" do + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, + event_handler, event_logger, variable_parser, audience_matcher) + context.refresh + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + + expect(context.ready?).to be true + expect(context.failed?).to be_falsey + expect(context.experiments).to eq(data.experiments.map(&:name)) + end + + it "keeps newer data a refresh installed when the initial fetch then succeeds late" do + events = [] + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) { |event, data| events << [event, data] } + end.new + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, + event_handler, logger, variable_parser, audience_matcher) + context.refresh + refreshed = context.data + stale = descr.deserialize('{"experiments":[]}', 0, 18) + context.set_data(OpenStruct.new(data_future: stale, success?: true)) + + expect(context.data).to equal(refreshed) + expect(events.last).to eq([ContextEventLogger::EVENT_TYPE::READY, refreshed]) + end + + it "logs only the error when the initial fetch fails on a context that is not ready" do + events = [] + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) { |event, _data| events << event } + end.new + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, + event_handler, logger, variable_parser, audience_matcher) + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + + expect(events).to eq([ContextEventLogger::EVENT_TYPE::ERROR]) + end + + it "logs ready when a refresh made the context ready and the initial fetch then fails" do + events = [] + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) { |event, _data| events << event } + end.new + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, + event_handler, logger, variable_parser, audience_matcher) + context.refresh + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + + expect(events).to eq([ContextEventLogger::EVENT_TYPE::REFRESH, ContextEventLogger::EVENT_TYPE::ERROR, + ContextEventLogger::EVENT_TYPE::READY]) + end + + it "keeps an in-flight refresh usable when the initial fetch fails before it completes" do + published = [] + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + published.concat((event.goals || []).map(&:name)) + OpenStruct.new(success?: true) + end + in_refresh = Queue.new + release = Queue.new + provider = Object.new + ready_data = data + provider.define_singleton_method(:context_data) do + in_refresh << true + release.pop + OpenStruct.new(data_future: ready_data, success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, + handler, event_logger, variable_parser, audience_matcher) + refresher = Thread.new { context.refresh } + begin + Timeout.timeout(5) { in_refresh.pop } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + expect(context.failed?).to be true + release << true + Timeout.timeout(5) { refresher.join } + ensure + release << true + refresher.join(5) || refresher.kill + end + + expect(context.failed?).to be false + expect(context.ready_error).to be_nil + context.track("goal1", nil) + context.publish + expect(published).to eq(["goal1"]) + end + + it "lets a variable parser call wait_until_ready while a refresh installs data" do + calls = [] + holder = {} + parser = Object.new + parser.define_singleton_method(:parse) do |context, _experiment, _variant, config| + calls << context.wait_until_ready(0).equal?(holder[:context]) if holder[:context] + JSON.parse(config, symbolize_names: true) + rescue JSON::ParserError + nil + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create(clock, context_config, OpenStruct.new(data_future: data, success?: true), + data_provider, event_handler, event_logger, parser, audience_matcher) + holder[:context] = context + allow(data_provider).to receive(:context_data).and_return(OpenStruct.new(data_future: data, success?: true)) + + expect { context.refresh }.not_to raise_error + expect(calls).not_to be_empty + expect(calls).to all(be true) + end + + it "lets a variable parser call wait_until_ready while the initial async data is installed" do + holder = {} + calls = [] + parser = Object.new + parser.define_singleton_method(:parse) do |context, _experiment, _variant, config| + calls << [context.wait_until_ready(0).equal?(holder[:context]), + context.wait_until_ready.equal?(holder[:context])] + JSON.parse(config, symbolize_names: true) + rescue JSON::ParserError + nil + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, + event_handler, event_logger, parser, audience_matcher) + holder[:context] = context + + expect { Timeout.timeout(5) { context.set_data(OpenStruct.new(data_future: data, success?: true)) } } + .not_to raise_error + expect(calls).not_to be_empty + expect(calls.flatten).to all(be true) + expect(context.ready?).to be true + end + + it "lets a variable parser call wait_until_ready from a fiber while the initial async data is installed" do + holder = {} + calls = [] + parser = Object.new + parser.define_singleton_method(:parse) do |context, _experiment, _variant, config| + calls << Fiber.new { context.wait_until_ready.equal?(holder[:context]) }.resume + JSON.parse(config, symbolize_names: true) + rescue JSON::ParserError + nil + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, + event_handler, event_logger, parser, audience_matcher) + holder[:context] = context + + expect { Timeout.timeout(5) { context.set_data(OpenStruct.new(data_future: data, success?: true)) } } + .not_to raise_error + expect(calls).not_to be_empty + expect(calls).to all(be true) + expect(context.ready?).to be true + expect(context.instance_variable_get(:@building_threads)).to be_empty + end + + it "does not hold the readiness lock while the variable parser runs" do + in_parser = Queue.new + release = Queue.new + parser = Object.new + parser.define_singleton_method(:parse) do |_context, _experiment, _variant, config| + unless Thread.current[:parsed] + Thread.current[:parsed] = true + in_parser << true + release.pop + end + JSON.parse(config, symbolize_names: true) + rescue JSON::ParserError + nil + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, + event_handler, event_logger, parser, audience_matcher) + installer = Thread.new { context.set_data(OpenStruct.new(data_future: data, success?: true)) } + begin + Timeout.timeout(5) { in_parser.pop } + expect(Timeout.timeout(1) { context.wait_until_ready(0) }).to equal(context) + expect(context.ready?).to be false + ensure + release << true + installer.join(5) || installer.kill + end + expect(context.ready?).to be true + end + + it "a publish that saw the context failed keeps goals tracked after a refresh recovered it" do + published = [] + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + published.concat((event.goals || []).map(&:name)) + OpenStruct.new(success?: true) + end + in_refresh = Queue.new + release_refresh = Queue.new + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) do + in_refresh << true + release_refresh.pop + OpenStruct.new(data_future: ready_data, success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, + handler, event_logger, variable_parser, audience_matcher) + + # A refresh is in flight when the initial fetch fails. A publish then + # sees the context failed and pauses before it drops the queue; the + # refresh recovers and a new goal is tracked before the publish resumes. + seen_failed = Queue.new + resume = Queue.new + ready_mutex = context.instance_variable_get(:@ready_mutex) + allow(ready_mutex).to receive(:synchronize).and_wrap_original do |original, &block| + if Thread.current[:role] == :publisher && !Thread.current[:paused] + Thread.current[:paused] = true + seen_failed << true + resume.pop + end + original.call(&block) + end + refresher = Thread.new { context.refresh } + publisher = nil + begin + Timeout.timeout(5) { in_refresh.pop } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + context.track("while_failed", nil) + publisher = Thread.new do + Thread.current[:role] = :publisher + context.publish + end + Timeout.timeout(5) { seen_failed.pop } + release_refresh << true + Timeout.timeout(5) { refresher.join } + expect(context.failed?).to be false + context.track("after_recovery", nil) + resume << true + Timeout.timeout(5) { publisher.join } + ensure + release_refresh << true + resume << true + [refresher, publisher].compact.each { |t| t.join(5) || t.kill } + end + + context.publish + expect(published).to include("after_recovery") + expect(context.pending_count).to eq(0) + end + + it "does not parse a late initial payload a refresh already superseded, and logs it as ready" do + parses = 0 + parser = Object.new + parser.define_singleton_method(:parse) do |_context, _experiment, _variant, config| + parses += 1 + JSON.parse(config, symbolize_names: true) + rescue JSON::ParserError + nil + end + events = [] + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) { |event, _data| events << event } + end.new + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, + event_handler, logger, parser, audience_matcher) + context.refresh + after_refresh = parses + context.set_data(OpenStruct.new(data_future: data, success?: true)) + + expect(parses).to eq(after_refresh) + expect(events).to eq([ContextEventLogger::EVENT_TYPE::REFRESH, ContextEventLogger::EVENT_TYPE::READY]) + end + + it "keeps refreshed data after an initial payload has already started parsing" do + parsing = Queue.new + release = Queue.new + parser = Object.new + parser.define_singleton_method(:parse) do |_c, _e, _v, config| + if Thread.current[:initial_build] && !Thread.current[:paused] + Thread.current[:paused] = true + parsing << true + release.pop + end + JSON.parse(config, symbolize_names: true) + rescue JSON::ParserError + nil + end + provider = Object.new + refreshed = DefaultContextDataDeserializer.new.deserialize( + '{"experiments":[]}', 0, 18 + ) + provider.define_singleton_method(:context_data) do + OpenStruct.new(data_future: refreshed, success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, + event_handler, event_logger, parser, audience_matcher) + installer = Thread.new do + Thread.current[:initial_build] = true + context.set_data(OpenStruct.new(data_future: data, success?: true)) + end + begin + Timeout.timeout(5) { parsing.pop } + context.refresh + release << true + Timeout.timeout(5) { installer.join } + ensure + release << true + installer.join(5) || installer.kill + end + expect(context.data).to equal(refreshed) + end + + def blocking_parser(in_parser, release, raise_first: false) + parser = Object.new + parser.define_singleton_method(:parse) do |_context, _experiment, _variant, config| + if Thread.current[:block_parse] && !Thread.current[:parsed] + Thread.current[:parsed] = true + in_parser << true + release.pop + raise "parser failed" if raise_first + end + JSON.parse(config, symbolize_names: true) + rescue JSON::ParserError + nil + end + parser + end + + it "keeps another thread's wait blocked while the initial data is still being built" do + in_parser = Queue.new + release = Queue.new + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, event_handler, event_logger, + blocking_parser(in_parser, release), audience_matcher) + installer = Thread.new do + Thread.current[:block_parse] = true + context.set_data(OpenStruct.new(data_future: data, success?: true)) + end + waiter = nil + begin + Timeout.timeout(5) { in_parser.pop } + waiter = Thread.new do + context.wait_until_ready + context.ready? + end + Timeout.timeout(5) { sleep 0.01 until waiter.status == "sleep" } + expect(waiter.alive?).to be true + release << true + expect(Timeout.timeout(5) { waiter.value }).to be true + ensure + release << true + [installer, waiter].compact.each { |t| t.join(5) || t.kill } + end + end + + it "lets a thread whose own build raised wait normally afterwards" do + in_parser = Queue.new + release = Queue.new + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, event_handler, event_logger, + blocking_parser(in_parser, release, raise_first: true), audience_matcher) + release << true + builder = Thread.new do + Thread.current[:block_parse] = true + begin + context.refresh + rescue RuntimeError => e + e + end + # This thread no longer builds anything: its wait must block until + # another thread installs the data, not return at once. + context.wait_until_ready + context.ready? + end + begin + Timeout.timeout(5) { in_parser.pop } + Timeout.timeout(5) { sleep 0.01 until builder.status == "sleep" } + expect(context.ready?).to be false + context.set_data(OpenStruct.new(data_future: data, success?: true)) + expect(Timeout.timeout(5) { builder.value }).to be true + ensure + builder.join(5) || builder.kill + end + end + + it "a concurrent failing refresh does not clear the initial builder's self-wait guard" do + a_in = Queue.new + b_done = Queue.new + waited = Queue.new + holder = {} + parser = Object.new + parser.define_singleton_method(:parse) do |_context, _experiment, _variant, config| + case Thread.current[:role] + when :a + unless Thread.current[:once] + Thread.current[:once] = true + a_in << true + b_done.pop + holder[:context].wait_until_ready + waited << true + end + when :b + raise "boom" + end + JSON.parse(config, symbolize_names: true) + rescue JSON::ParserError + nil + end + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) { OpenStruct.new(data_future: ready_data, success?: true) } + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, event_handler, event_logger, + parser, audience_matcher) + holder[:context] = context + a = Thread.new do + Thread.current[:role] = :a + context.set_data(provider.context_data) + end + b = nil + begin + Timeout.timeout(5) { a_in.pop } + b = Thread.new do + Thread.current[:role] = :b + begin + context.refresh + rescue RuntimeError + nil + end + end + Timeout.timeout(5) { b.join } + b_done << true + expect(Timeout.timeout(5) { waited.pop }).to be true + Timeout.timeout(5) { a.join } + expect(context.ready?).to be true + ensure + b_done << true + [a, b].compact.each { |t| t.join(5) || t.kill } + end + end + + it "a nested build on the same thread keeps the outer builder's membership" do + holder = {} + results = [] + parser = Object.new + parser.define_singleton_method(:parse) do |_context, _experiment, _variant, config| + if holder[:context] && !Thread.current[:nested] + Thread.current[:nested] = true + holder[:context].refresh + results << holder[:context].wait_until_ready.equal?(holder[:context]) + end + JSON.parse(config, symbolize_names: true) + rescue JSON::ParserError + nil + end + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) { OpenStruct.new(data_future: ready_data, success?: true) } + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, event_handler, event_logger, + parser, audience_matcher) + holder[:context] = context + Timeout.timeout(5) { context.set_data(provider.context_data) } + + expect(results).to eq([true]) + expect(context.ready?).to be true + expect(context.instance_variable_get(:@building_threads)).to be_empty + end + + it "an in-flight publish removes only its own batch after a failed-context clear and recovery" do + publish_in = Queue.new + publish_out = Queue.new + refresh_in = Queue.new + refresh_out = Queue.new + sent = [] + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + names = (event.goals || []).map(&:name) + sent << names + if names.include?("before_failure") + publish_in << true + publish_out.pop + end + OpenStruct.new(success?: true) + end + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) do + refresh_in << true + refresh_out.pop + OpenStruct.new(data_future: ready_data, success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, handler, event_logger, + variable_parser, audience_matcher) + context.track("before_failure", nil) + a = Thread.new { context.publish } + b = nil + begin + Timeout.timeout(5) { publish_in.pop } + b = Thread.new { context.refresh } + Timeout.timeout(5) { refresh_in.pop } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + context.publish + refresh_out << true + Timeout.timeout(5) { b.join } + context.track("after_recovery", nil) + publish_out << true + Timeout.timeout(5) { a.join } + + expect(context.pending_count).to eq(1) + context.publish + expect(sent).to eq([["before_failure"], ["after_recovery"]]) + expect(context.pending_count).to eq(0) + ensure + refresh_out << true + publish_out << true + [a, b].compact.each { |t| t.join(5) || t.kill } + end + end + + it "an in-flight publish removes only its own exposures after a failed-context clear and recovery" do + publish_in = Queue.new + publish_out = Queue.new + refresh_in = Queue.new + refresh_out = Queue.new + sent = [] + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + names = (event.exposures || []).map(&:name) + sent << names + if names.include?("exp_test_ab") + publish_in << true + publish_out.pop + end + OpenStruct.new(success?: true) + end + ready_data = data + fetches = 0 + provider = Object.new + provider.define_singleton_method(:context_data) do + fetches += 1 + if fetches > 1 + refresh_in << true + refresh_out.pop + end + OpenStruct.new(data_future: ready_data, success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, handler, event_logger, + variable_parser, audience_matcher) + context.set_data(provider.context_data) + context.treatment("exp_test_ab") + a = Thread.new { context.publish } + b = nil + begin + Timeout.timeout(5) { publish_in.pop } + b = Thread.new { context.refresh } + Timeout.timeout(5) { refresh_in.pop } + context.instance_variable_get(:@ready_mutex).synchronize { context.send(:set_data_failed, failure) } + context.publish + refresh_out << true + Timeout.timeout(5) { b.join } + context.treatment("exp_test_abc") + publish_out << true + Timeout.timeout(5) { a.join } + + expect(context.pending_count).to eq(1) + context.publish + expect(sent).to eq([["exp_test_ab"], ["exp_test_abc"]]) + expect(context.pending_count).to eq(0) + ensure + refresh_out << true + publish_out << true + [a, b].compact.each { |t| t.join(5) || t.kill } + end + end + + it "keeps an exposure queued while a publish is in flight for the next publish" do + publish_in = Queue.new + publish_out = Queue.new + sent = [] + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + names = (event.exposures || []).map(&:name) + sent << names + if names.include?("exp_test_ab") + publish_in << true + publish_out.pop + end + OpenStruct.new(success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create(clock, context_config, OpenStruct.new(data_future: data, success?: true), + data_provider, handler, event_logger, variable_parser, audience_matcher) + context.treatment("exp_test_ab") + publisher = Thread.new { context.publish } + begin + Timeout.timeout(5) { publish_in.pop } + context.treatment("exp_test_abc") + publish_out << true + Timeout.timeout(5) { publisher.join } + + expect(context.pending_count).to eq(1) + context.publish + expect(sent).to eq([["exp_test_ab"], ["exp_test_abc"]]) + expect(context.pending_count).to eq(0) + ensure + publish_out << true + publisher.join(5) || publisher.kill + end + end + + it "a goal tracked after recovery is never dropped by a failed-context clear" do + sent = [] + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + sent.concat((event.goals || []).map(&:name)) + OpenStruct.new(success?: true) + end + refresh_in = Queue.new + refresh_out = Queue.new + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) do + refresh_in << true + refresh_out.pop + OpenStruct.new(data_future: ready_data, success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, handler, event_logger, + variable_parser, audience_matcher) + # Pause the publisher at its queue-lock call inside the failed path: the + # clear must happen under the readiness lock, so a recovering refresh + # either finishes first (no clear) or waits for the clear to finish. + at_clear = Queue.new + resume = Queue.new + queue_mutex = context.instance_variable_get(:@queue_mutex) + allow(queue_mutex).to receive(:synchronize).and_wrap_original do |original, &block| + if Thread.current[:role] == :publisher && !Thread.current[:paused] + Thread.current[:paused] = true + at_clear << true + resume.pop + end + original.call(&block) + end + refresher = Thread.new { context.refresh } + publisher = nil + begin + Timeout.timeout(5) { refresh_in.pop } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + publisher = Thread.new do + Thread.current[:role] = :publisher + context.publish + end + Timeout.timeout(5) { at_clear.pop } + refresh_out << true + expect(refresher.join(0.5)).to be_nil + expect(context.failed?).to be true + context.track("probe", nil) + resume << true + Timeout.timeout(5) { publisher.join } + Timeout.timeout(5) { refresher.join } + expect(context.failed?).to be false + context.track("after", nil) + context.publish + expect(sent).to include("after") + ensure + refresh_out << true + resume << true + [refresher, publisher].compact.each { |t| t.join(5) || t.kill } + end + end + + it "finalize does not raise the initial-fetch error when a refresh recovers during its flush" do + refresh_in = Queue.new + refresh_out = Queue.new + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) do + refresh_in << true + refresh_out.pop + OpenStruct.new(data_future: ready_data, success?: true) + end + handler = Object.new + handler.define_singleton_method(:publish) { |_context, _event| OpenStruct.new(success?: true) } + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, handler, event_logger, + variable_parser, audience_matcher) + refresher = Thread.new { context.refresh } + Timeout.timeout(5) { refresh_in.pop } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + + # The refresh recovers right after finalize's flush returned the load error. + original = context.method(:flush) + allow(context).to receive(:flush) do |**kwargs| + result = original.call(**kwargs) + if kwargs[:sealing] && !refresher.status.nil? && refresher.alive? + refresh_out << true + Timeout.timeout(5) { refresher.join } + end + result + end + begin + expect { Timeout.timeout(5) { context.finalize } }.not_to raise_error + ensure + refresh_out << true + refresher.join(5) || refresher.kill + end + expect(context.failed?).to be false + end + + it "resolves assignments made while failed against the recovered data" do + exposures = [] + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + exposures.concat((event.exposures || []).map { |e| [e.name, e.id, e.variant] }) + OpenStruct.new(success?: true) + end + in_refresh = Queue.new + release = Queue.new + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) do + in_refresh << true + release.pop + OpenStruct.new(data_future: ready_data, success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, + handler, event_logger, variable_parser, audience_matcher) + refresher = Thread.new { context.refresh } + begin + Timeout.timeout(5) { in_refresh.pop } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + context.set_override("exp_test_ab", 1) + expect(context.peek_treatment("exp_test_ab")).to eq(1) + # A second assignment built while failed: marking one must not + # unmark another. + expect(context.peek_treatment("exp_test_abc")).to eq(0) + release << true + Timeout.timeout(5) { refresher.join } + ensure + release << true + refresher.join(5) || refresher.kill + end + + expect(context.failed?).to be false + expect(context.variable_value("banner.size", "default")).to eq("large") + expect(context.variable_value("button.color", "default")).not_to eq("default") + context.publish + expect(exposures.map(&:first)).to eq(%w[exp_test_ab exp_test_abc]) + expect(exposures.first).to eq(["exp_test_ab", 1, 1]) + expect(exposures.last[1]).to eq(2) + end + + it "does not keep an assignment a read built from the failed snapshot after recovery" do + exposures = [] + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + exposures.concat((event.exposures || []).map { |e| [e.name, e.id, e.variant] }) + OpenStruct.new(success?: true) + end + in_refresh = Queue.new + release = Queue.new + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) do + in_refresh << true + release.pop + OpenStruct.new(data_future: ready_data, success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, + handler, event_logger, variable_parser, audience_matcher) + refresher = Thread.new { context.refresh } + begin + Timeout.timeout(5) { in_refresh.pop } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + failed_state = context.instance_variable_get(:@state) + context.set_override("exp_test_ab", 1) + release << true + Timeout.timeout(5) { refresher.join } + ensure + release << true + refresher.join(5) || refresher.kill + end + # A reader that captured the failed snapshot before the refresh committed + # finishes only after the recovery installed the recovered data. + cache = context.instance_variable_get(:@assignment_cache) + expect(cache).to be_empty + stale_read(context, "exp_test_ab", failed_state) + expect(cache).to be_empty + + expect(context.variable_value("banner.size", "default")).to eq("large") + context.publish + expect(exposures).to eq([["exp_test_ab", 1, 1]]) + end + + it "keeps one exposure for a read that raced an ordinary refresh" do + exposures = [] + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + exposures.concat((event.exposures || []).map { |e| [e.name, e.id, e.variant] }) + OpenStruct.new(success?: true) + end + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) { OpenStruct.new(data_future: ready_data, success?: true) } + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create(clock, context_config, OpenStruct.new(data_future: data, success?: true), provider, + handler, event_logger, variable_parser, audience_matcher) + old_state = context.instance_variable_get(:@state) + context.refresh + %w[exp_test_ab not_found].each do |name| + context.send(:queue_exposure, stale_read(context, name, old_state)) + context.treatment(name) + end + context.publish + + expect(exposures.map(&:first)).to eq(%w[exp_test_ab not_found]) + expect(exposures.last).to eq(["not_found", 0, 0]) + end + + it "reuses an assignment while the context stays failed" do + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, + event_handler, event_logger, variable_parser, audience_matcher) + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + context.set_override("exp_test_ab", 1) + context.treatment("exp_test_ab") + context.treatment("exp_test_ab") + + expect(context.pending_count).to eq(1) + end + + describe "a read still on the failed snapshot after a refresh recovered the context" do + let(:exposures) { [] } + + def recovered_context + sent = exposures + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + sent.concat((event.exposures || []).map { |e| [e.name, e.id, e.variant] }) + OpenStruct.new(success?: true) + end + in_refresh = Queue.new + release = Queue.new + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) do + in_refresh << true + release.pop + OpenStruct.new(data_future: ready_data, success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, + handler, event_logger, variable_parser, audience_matcher) + refresher = Thread.new { context.refresh } + begin + Timeout.timeout(5) { in_refresh.pop } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + failed_state = context.instance_variable_get(:@state) + yield context if block_given? + release << true + Timeout.timeout(5) { refresher.join } + ensure + release << true + refresher.join(5) || refresher.kill + end + [context, failed_state] + end + + it "does not cause a second exposure of a recovered assignment" do + context, failed_state = recovered_context + context.treatment("exp_test_ab") + stale_read(context, "exp_test_ab", failed_state) + context.treatment("exp_test_ab") + context.publish + + expect(exposures.size).to eq(1) + expect(exposures.first[0..1]).to eq(["exp_test_ab", 1]) + end + + it "keeps it when the recovered data lacks the experiment too" do + context, failed_state = recovered_context + context.send(:queue_exposure, stale_read(context, "not_found", failed_state)) + context.treatment("not_found") + context.publish + + expect(exposures).to eq([["not_found", 0, 0]]) + end + + it "keeps a forced one when the recovered data lacks the experiment too" do + context, failed_state = recovered_context { |ctx| ctx.set_override("not_found", 2) } + context.send(:queue_exposure, stale_read(context, "not_found", failed_state)) + expect(context.treatment("not_found")).to eq(2) + context.publish + + expect(exposures).to eq([["not_found", 0, 2]]) + end + + it "reuses the assignment exposed while failed" do + context, failed_state = recovered_context { |ctx| ctx.treatment("exp_test_ab") } + context.send(:queue_exposure, stale_read(context, "exp_test_ab", failed_state)) + context.publish + + expect(exposures).to eq([["exp_test_ab", 0, 0]]) + end + end + + it "does not mark or check assignments on cached reads of a context that never failed" do + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create(clock, context_config, OpenStruct.new(data_future: data, success?: true), + data_provider, event_handler, event_logger, variable_parser, audience_matcher) + context.peek_treatment("exp_test_ab") + assignment = context.instance_variable_get(:@assignment_cache)["exp_test_ab"] + expect(assignment.instance_variable_get(:@failed_snapshot)).to be false + expect(assignment).not_to receive(:instance_variable_get) + 3.times { context.peek_treatment("exp_test_ab") } + end + + it "keeps a failed-snapshot assignment ineligible for reuse when its rebuild raises" do + exposures = [] + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + exposures.concat((event.exposures || []).map { |e| [e.name, e.id, e.variant] }) + OpenStruct.new(success?: true) + end + in_refresh = Queue.new + release = Queue.new + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) do + in_refresh << true + release.pop + OpenStruct.new(data_future: ready_data, success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, + handler, event_logger, variable_parser, audience_matcher) + refresher = Thread.new { context.refresh } + begin + Timeout.timeout(5) { in_refresh.pop } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + context.set_override("exp_test_ab", 1) + context.peek_treatment("exp_test_ab") + release << true + Timeout.timeout(5) { refresher.join } + ensure + release << true + refresher.join(5) || refresher.kill + end + context.instance_variable_get(:@overrides).delete(:exp_test_ab) + allow(VariantAssigner).to receive(:new).and_raise(RuntimeError, "matcher failed") + expect { context.treatment("exp_test_ab") }.to raise_error(RuntimeError, "matcher failed") + allow(VariantAssigner).to receive(:new).and_call_original + context.set_override("exp_test_ab", 1) + + expect(context.variable_value("banner.size", "default")).to eq("large") + context.publish + expect(exposures).to eq([["exp_test_ab", 1, 1]]) + end + + it "does not expose again an experiment the recovered data still lacks" do + exposures = [] + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + exposures.concat((event.exposures || []).map { |e| [e.name, e.id, e.variant] }) + OpenStruct.new(success?: true) + end + in_refresh = Queue.new + release = Queue.new + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) do + in_refresh << true + release.pop + OpenStruct.new(data_future: ready_data, success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, + handler, event_logger, variable_parser, audience_matcher) + refresher = Thread.new { context.refresh } + begin + Timeout.timeout(5) { in_refresh.pop } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + context.treatment("not_found") + context.treatment("exp_test_ab") + release << true + Timeout.timeout(5) { refresher.join } + ensure + release << true + refresher.join(5) || refresher.kill + end + context.treatment("not_found") + context.treatment("exp_test_ab") + context.publish + + expect(exposures).to eq([["not_found", 0, 0], ["exp_test_ab", 0, 0], ["exp_test_ab", 1, 1]]) + end + + it "honors a cleared override after recovery still lacks the experiment" do + in_refresh = Queue.new + release = Queue.new + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) do + in_refresh << true + release.pop + OpenStruct.new(data_future: ready_data, success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, + event_handler, event_logger, variable_parser, audience_matcher) + refresher = Thread.new { context.refresh } + begin + Timeout.timeout(5) { in_refresh.pop } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + context.set_override("not_found", 1) + expect(context.treatment("not_found")).to eq(1) + release << true + Timeout.timeout(5) { refresher.join } + ensure + release << true + refresher.join(5) || refresher.kill + end + context.set_override("not_found", nil) + + expect(context.treatment("not_found")).to eq(0) + end + + it "resolves an assignment made while failed once a later refresh supplies the experiment" do + exposures = [] + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + exposures.concat((event.exposures || []).map { |e| [e.name, e.id, e.variant] }) + OpenStruct.new(success?: true) + end + in_refresh = Queue.new + release = Queue.new + payloads = [ContextData.new, data] + provider = Object.new + provider.define_singleton_method(:context_data) do + in_refresh << true + release.pop + OpenStruct.new(data_future: payloads.shift, success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, + handler, event_logger, variable_parser, audience_matcher) + refresher = Thread.new { context.refresh } + begin + Timeout.timeout(5) { in_refresh.pop } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + context.set_override("exp_test_ab", 1) + expect(context.treatment("exp_test_ab")).to eq(1) + release << true + Timeout.timeout(5) { refresher.join } + ensure + release << true + refresher.join(5) || refresher.kill + end + expect(context.failed?).to be false + expect(context.variable_value("banner.size", "default")).to eq("default") + + release << true + expect { context.refresh }.not_to raise_error + expect(context.treatment("exp_test_ab")).to eq(1) + values = Array.new(3) { context.variable_value("banner.size", "default") } + expect(context.treatment("exp_test_ab")).to eq(1) + context.publish + + # Owner decision: after the later refresh either outcome is accepted. + # Resolved again: one new exposure with the real experiment id, and the + # recovered variant's variables. Kept (as java-sdk and javascript-sdk + # keep the cached id-0 assignment): no new exposure, and the default. + # The override's variant is served either way, reads stay stable, and + # nothing is exposed twice. + expect(exposures.first).to eq(["exp_test_ab", 0, 1]) + expect(values.uniq.size).to eq(1) + expect([exposures.drop(1), values.first]) + .to eq([[["exp_test_ab", 1, 1]], "large"]).or eq([[], "default"]) + end + + it "keeps a failed assignment ineligible when an interrupt lands while its replacement is cached" do + exposures = [] + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + exposures.concat((event.exposures || []).map { |e| [e.name, e.id, e.variant] }) + OpenStruct.new(success?: true) + end + in_refresh = Queue.new + release = Queue.new + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) do + in_refresh << true + release.pop + OpenStruct.new(data_future: ready_data, success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, + handler, event_logger, variable_parser, audience_matcher) + refresher = Thread.new { context.refresh } + begin + Timeout.timeout(5) { in_refresh.pop } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + context.set_override("exp_test_ab", 1) + context.treatment("exp_test_ab") + release << true + Timeout.timeout(5) { refresher.join } + ensure + release << true + refresher.join(5) || refresher.kill + end + untagging = Queue.new + resume = Queue.new + cache = context.instance_variable_get(:@assignment_cache) + old_assignment = cache["exp_test_ab"] + cache.define_singleton_method(:[]=) do |key, value| + result = super(key, value) + if Thread.current[:gate] + Thread.current[:gate] = false + untagging << true + resume.pop + end + result + end + reader = Thread.new do + Thread.current[:gate] = true + context.variable_value("banner.size", "default") + rescue Interrupt + nil + end + Timeout.timeout(5) { untagging.pop } + reader.raise(Interrupt) + resume << true + Timeout.timeout(5) { reader.join } + + expect(old_assignment.instance_variable_get(:@failed_snapshot)).to be true + 3.times { expect(context.variable_value("banner.size", "default")).to eq("large") } + context.publish + expect(exposures).to eq([["exp_test_ab", 0, 1], ["exp_test_ab", 1, 1]]) + end + + it "never caches an unmarked failed assignment when an interrupt lands while a failed read is cached" do + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, + event_handler, event_logger, variable_parser, audience_matcher) + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + tagging = Queue.new + resume = Queue.new + cache = context.instance_variable_get(:@assignment_cache) + cache.define_singleton_method(:[]=) do |key, value| + result = super(key, value) + if Thread.current[:gate] + Thread.current[:gate] = false + tagging << true + resume.pop + end + result + end + reader = Thread.new do + Thread.current[:gate] = true + context.peek_treatment("exp_test_ab") + rescue Interrupt + nil + end + Timeout.timeout(5) { tagging.pop } + reader.raise(Interrupt) + resume << true + Timeout.timeout(5) { reader.join } + + cache = context.instance_variable_get(:@assignment_cache) + expect(cache.values).not_to be_empty + expect(cache.values).to all(satisfy { |cached| cached.instance_variable_get(:@failed_snapshot) }) + end + + # Each gate parks refresh on a line and interrupts it there: just after the + # snapshot install inside the mask, and the first line after the mask. + { + "inside the recovery commit" => ["@state = state", 2, "@failed = false"], + "right after the recovery commit" => ["@ready_condvar.broadcast", 4, + "log_event(ContextEventLogger::EVENT_TYPE::REFRESH, data_future.data_future)"] + }.each do |where, (anchor, offset, gated)| + it "completes recovery when an interrupt lands #{where}" do + sent = [] + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + sent.concat((event.goals || []).map(&:name)) + OpenStruct.new(success?: true) + end + in_refresh = Queue.new + release = Queue.new + ready_data = data + calls = 0 + provider = Object.new + provider.define_singleton_method(:context_data) do + calls += 1 + if calls == 1 + in_refresh << true + release.pop + end + OpenStruct.new(data_future: ready_data, success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, + handler, event_logger, variable_parser, audience_matcher) + source, start = Context.instance_method(:refresh).source_location + lines = File.readlines(source) + commit_line = lines.each_with_index.find { |line, index| index >= start && line.strip == anchor }.last + offset + expect(lines[commit_line - 1].strip).to eq(gated) + committing = Queue.new + resume_commit = Queue.new + trace = TracePoint.new(:line) do |event| + if event.path == source && event.lineno == commit_line && Thread.current[:gate] + Thread.current[:gate] = false + committing << true + resume_commit.pop + end + end + trace.enable + refresher = Thread.new do + Thread.current[:gate] = true + context.refresh + rescue Interrupt + nil + end + begin + Timeout.timeout(5) { in_refresh.pop } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + release << true + Timeout.timeout(5) { committing.pop } + refresher.raise(Interrupt) + resume_commit << true + Timeout.timeout(5) { refresher.join } + ensure + trace.disable + resume_commit << true + release << true + refresher.join(5) || refresher.kill + end + + expect(context.failed?).to be false + expect(context.ready_error).to be_nil + expect(context.data).to equal(data) + context.track("after_recovery", nil) + context.publish + expect(sent).to eq(["after_recovery"]) + context.refresh + expect(calls).to eq(2) + end + end + + it "does not mask an unrelated cache write while a failed-snapshot assignment remains" do + in_refresh = Queue.new + release = Queue.new + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) do + in_refresh << true + release.pop + OpenStruct.new(data_future: ready_data, success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, + event_handler, event_logger, variable_parser, audience_matcher) + refresher = Thread.new { context.refresh } + begin + Timeout.timeout(5) { in_refresh.pop } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + context.peek_treatment("not_found") + release << true + Timeout.timeout(5) { refresher.join } + ensure + release << true + refresher.join(5) || refresher.kill + end + expect(context.failed?).to be false + cached = context.instance_variable_get(:@assignment_cache)["not_found"] + expect(cached.instance_variable_get(:@failed_snapshot)).to be true + + masks = 0 + allow(Thread).to receive(:handle_interrupt).and_wrap_original do |original, *args, &block| + masks += 1 + original.call(*args, &block) + end + context.peek_treatment("exp_test_ab") + expect(masks).to eq(0) + context.set_override("exp_test_ab", 2) + context.peek_treatment("exp_test_ab") + expect(masks).to eq(0) + end + + # The second operation waits behind a publish the collector rejects; the + # initial fetch fails and a goal is tracked before it takes its turn. + [ + ["a publish waiting for an in-flight one does not send events after the initial fetch failed", + :publish, ->(result, failure, context) { + expect(result).to equal(failure) + expect(context.failed?).to be true + }], + ["a finalize waiting for an in-flight publish seals without sending events after the initial fetch failed", + :finalize, ->(result, _failure, context) { + expect(result).to be_nil + expect(context.finalized?).to be true + }] + ].each do |label, operation, outcome| + it label do + sent = [] + in_publish = Queue.new + release = Queue.new + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + sent << (event.goals || []).map(&:name) + if sent.size == 1 + in_publish << true + release.pop + next OpenStruct.new(success?: false, status: 503) + end + OpenStruct.new(success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, + handler, event_logger, variable_parser, audience_matcher) + context.track("before_failure", nil) + first = Thread.new { context.publish } + second = nil + result = nil + begin + Timeout.timeout(5) { in_publish.pop } + second = Thread.new { context.public_send(operation) } + Timeout.timeout(5) { Thread.pass until second.status == "sleep" } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + context.track("after_failure", nil) + release << true + Timeout.timeout(5) { first.join } + result = Timeout.timeout(5) { second.value } + ensure + release << true + first.join(5) || first.kill + second&.join(5) || second&.kill + end + + instance_exec(result, failure, context, &outcome) + expect(sent).to eq([["before_failure"]]) + expect(context.pending_count).to eq(0) + end + end + + it "does not send exposures a publish dropped while failed once a refresh recovers" do + exposures = [] + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + exposures.concat((event.exposures || []).map(&:name)) + OpenStruct.new(success?: true) + end + in_refresh = Queue.new + release = Queue.new + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) do + in_refresh << true + release.pop + OpenStruct.new(data_future: ready_data, success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, + handler, event_logger, variable_parser, audience_matcher) + refresher = Thread.new { context.refresh } + begin + Timeout.timeout(5) { in_refresh.pop } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + context.treatment("while_failed_exp") + expect(context.publish).to equal(failure) + release << true + Timeout.timeout(5) { refresher.join } + ensure + release << true + refresher.join(5) || refresher.kill + end + context.treatment("exp_test_ab") + context.publish + + expect(exposures).to eq(["exp_test_ab"]) + end + + %i[publish finalize].each do |operation| + it "keeps failure installation outside #{operation}'s batch-selection boundary" do + sent = [] + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + sent.concat((event.goals || []).map(&:name)) + sent.concat((event.exposures || []).map(&:name)) + OpenStruct.new(success?: true) + end + config = ContextConfig.create + config.set_units(units) + context = Context.create_async(clock, config, data_provider, + handler, event_logger, variable_parser, audience_matcher) + context.track("before_failure", nil) + early = Assignment.new + early.name = "before_failure_exp" + context.queue_exposure(early) + # Each copy is part of the failure/selection transaction, including a + # copy moved earlier than the scheduling gate below. + %i[@achievements @exposures].each do |name| + array = context.instance_variable_get(name) + allow(array).to receive(:dup).and_wrap_original do |original| + expect(context.instance_variable_get(:@ready_mutex).owned?).to be true + original.call + end + end + # Park the publisher the moment it releases the readiness lock that + # covers its failure check and batch selection, then fail the fetch and + # queue a late goal and exposure; the dup spies above pin the copies. + ready_mutex = context.instance_variable_get(:@ready_mutex) + publish_mutex = context.instance_variable_get(:@publish_mutex) + queue_mutex = context.instance_variable_get(:@queue_mutex) + parked = Queue.new + resume = Queue.new + released = false + allow(ready_mutex).to receive(:synchronize).and_wrap_original do |original, &block| + result = original.call(&block) + if Thread.current[:gate_selection] && publish_mutex.owned? + Thread.current[:gate_selection] = false + released = true + parked << true + resume.pop + end + result + end + # A copy taken under the queue lock alone, before that readiness lock + # is taken, would also be outside the boundary: park there too. + allow(queue_mutex).to receive(:synchronize).and_wrap_original do |original, &block| + if Thread.current[:gate_selection] && publish_mutex.owned? && !ready_mutex.owned? && !released + Thread.current[:gate_selection] = false + parked << true + resume.pop + end + original.call(&block) + end + publisher = Thread.new do + Thread.current[:gate_selection] = true + context.public_send(operation) + end + begin + Timeout.timeout(5) { parked.pop } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + context.track("after_failure", nil) + late = Assignment.new + late.name = "after_failure_exp" + context.queue_exposure(late) + resume << true + Timeout.timeout(5) { publisher.join } + ensure + resume << true + publisher.join(1) || publisher.kill + end + expect(sent).to eq(["before_failure", "before_failure_exp"]) + end + end + + it "lets a supplied exposure clock wait for readiness during concurrent batch selection" do + entered = Queue.new + resume = Queue.new + custom_clock = Object.new + custom_clock.define_singleton_method(:to_i) do + if Thread.current[:clock_gate] + Thread.current[:clock_gate] = false + entered << true + resume.pop + context.wait_until_ready(0) + end + 123 + end + config = ContextConfig.create + config.set_units(units) + context = Context.create(custom_clock, config, OpenStruct.new(data_future: data, success?: true), + data_provider, event_handler, event_logger, variable_parser, audience_matcher) + custom_clock.define_singleton_method(:context) { context } + exposure = Thread.new do + Thread.current[:clock_gate] = true + context.treatment("exp_test_ab") + end + publisher = nil + begin + Timeout.timeout(5) { entered.pop } + context.track("goal", nil) + publisher = Thread.new { context.publish } + # Publish must complete without waiting for the clock callback. + Timeout.timeout(2) { publisher.value } + resume << true + Timeout.timeout(2) { exposure.value } + ensure + resume << true + exposure.join(2) || exposure.kill + publisher&.join(2) || publisher&.kill + end + end + + it "calls the supplied exposure clock only for a new exposure" do + calls = 0 + custom_clock = Object.new + custom_clock.define_singleton_method(:to_i) { calls += 1; 123 } + config = ContextConfig.create + config.set_units(units) + context = Context.create(custom_clock, config, OpenStruct.new(data_future: data, success?: true), + data_provider, event_handler, event_logger, variable_parser, audience_matcher) + 3.times { context.treatment("exp_test_ab") } + expect(calls).to eq(1) + end + + it "calls an exposure clock once across concurrent reads and allows clock reentry" do + entered = Queue.new + resume = Queue.new + calls = 0 + custom_clock = Object.new + context = nil + custom_clock.define_singleton_method(:to_i) do + calls += 1 + context.treatment("exp_test_ab") + entered << true + resume.pop + 123 + end + config = ContextConfig.create + config.set_units(units) + context = Context.create(custom_clock, config, OpenStruct.new(data_future: data, success?: true), + data_provider, event_handler, event_logger, variable_parser, audience_matcher) + first = Thread.new { context.treatment("exp_test_ab") } + second = nil + begin + Timeout.timeout(5) { entered.pop } + second = Thread.new { context.treatment("exp_test_ab") } + expect(second.join(0.1)).to be_nil + resume << true + Timeout.timeout(5) { first.value; second.value } + ensure + resume << true + first.join(2) || first.kill + second&.join(2) || second&.kill + end + expect(calls).to eq(1) + expect(context.pending_count).to eq(1) + end + + it "can retry exposure after the supplied clock raises" do + calls = 0 + custom_clock = Object.new + custom_clock.define_singleton_method(:to_i) do + calls += 1 + raise "clock failed" if calls == 1 + + 123 + end + config = ContextConfig.create + config.set_units(units) + context = Context.create(custom_clock, config, OpenStruct.new(data_future: data, success?: true), + data_provider, event_handler, event_logger, variable_parser, audience_matcher) + expect { context.treatment("exp_test_ab") }.to raise_error("clock failed") + expect(context.pending_count).to eq(0) + context.treatment("exp_test_ab") + expect(context.pending_count).to eq(1) + end + + it "allows a clock to wait for a distinct concurrent treatment and preserves both exposures" do + custom_clock = Object.new + context = nil + custom_clock.define_singleton_method(:to_i) do + if Thread.current[:outer_clock] + Thread.current[:outer_clock] = false + Timeout.timeout(2) { Thread.new { context.treatment("exp_test_abc") }.value } + end + 123 + end + names = [] + handler = Object.new + handler.define_singleton_method(:publish) do |_context, event| + names.concat((event.exposures || []).map(&:name)) + OpenStruct.new(success?: true) + end + config = ContextConfig.create + config.set_units(units) + context = Context.create(custom_clock, config, OpenStruct.new(data_future: data, success?: true), + data_provider, handler, event_logger, variable_parser, audience_matcher) + begin + Thread.current[:outer_clock] = true + context.treatment("exp_test_ab") + ensure + Thread.current[:outer_clock] = nil + end + expect(context.pending_count).to eq(2) + context.publish + expect(names).to eq(%w[exp_test_abc exp_test_ab]) + end + + it "does not enqueue an exposure after close seals during its clock callback" do + custom_clock = Object.new + context = nil + custom_clock.define_singleton_method(:to_i) { context.close; 123 } + config = ContextConfig.create + config.set_units(units) + context = Context.create(custom_clock, config, OpenStruct.new(data_future: data, success?: true), + data_provider, event_handler, event_logger, variable_parser, audience_matcher) + expect { context.treatment("exp_test_ab") }.to raise_error(IllegalStateException) + expect(context.pending_count).to eq(0) + expect(context.instance_variable_get(:@exposing)).to be_empty + end + + it "lets a competing exposure retry when the first clock fails" do + entered = Queue.new + resume = Queue.new + calls = 0 + custom_clock = Object.new + custom_clock.define_singleton_method(:to_i) do + calls += 1 + if calls == 1 + entered << true + resume.pop + raise "clock failed" + end + 123 + end + config = ContextConfig.create + config.set_units(units) + context = Context.create(custom_clock, config, OpenStruct.new(data_future: data, success?: true), + data_provider, event_handler, event_logger, variable_parser, audience_matcher) + first = Thread.new { context.treatment("exp_test_ab") rescue nil } + second = nil + begin + Timeout.timeout(5) { entered.pop } + second = Thread.new { context.treatment("exp_test_ab") } + expect(second.join(0.1)).to be_nil + resume << true + Timeout.timeout(5) { first.value; second.value } + ensure + resume << true + first.join(2) || first.kill + second&.join(2) || second&.kill + end + expect(context.pending_count).to eq(1) + expect(calls).to eq(2) + end + + it "lets an exposure waiter time out while the owning clock is blocked" do + entered = Queue.new + resume = Queue.new + custom_clock = Object.new + custom_clock.define_singleton_method(:to_i) { entered << true; resume.pop; 123 } + config = ContextConfig.create + config.set_units(units) + context = Context.create(custom_clock, config, OpenStruct.new(data_future: data, success?: true), + data_provider, event_handler, event_logger, variable_parser, audience_matcher) + owner = Thread.new { context.treatment("exp_test_ab") } + begin + Timeout.timeout(5) { entered.pop } + expect { Timeout.timeout(0.1) { context.treatment("exp_test_ab") } }.to raise_error(Timeout::Error) + ensure + resume << true + owner.join(2) || owner.kill + end + expect(context.pending_count).to eq(1) + end + + it "keeps failed-snapshot provenance on the cached assignment only" do + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, + event_handler, event_logger, variable_parser, audience_matcher) + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + 50.times do |i| + context.set_override("exp_test_ab", i % 2) + context.peek_treatment("exp_test_ab") + end + + cache = context.instance_variable_get(:@assignment_cache) + expect(cache.size).to eq(1) + expect(cache.values.first.instance_variable_get(:@failed_snapshot)).to be true + expect(context.instance_variable_defined?(:@failed_built)).to be false + end + + it "lets a timeout interrupt a slow variable parser" do + parser = DefaultVariableParser.new + parser.define_singleton_method(:parse) do |context, experiment, variant, config| + sleep 2 + super(context, experiment, variant, config) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, event_handler, event_logger, + parser, audience_matcher) + + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + expect { Timeout.timeout(0.1) { context.set_data(OpenStruct.new(data_future: data, success?: true)) } } + .to raise_error(Timeout::Error) + expect(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).to be < 1 + expect(context.instance_variable_get(:@building_threads)).to be_empty + end + + it "keeps a caller's interrupt mask while a refresh parses variables" do + parsing = Queue.new + parser = DefaultVariableParser.new + parser.define_singleton_method(:parse) do |context, experiment, variant, config| + parsing << true if Thread.current[:signal_parse] + sleep 0.05 if Thread.current[:signal_parse] + super(context, experiment, variant, config) + end + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) { OpenStruct.new(data_future: ready_data, success?: true) } + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create(clock, context_config, OpenStruct.new(data_future: data, success?: true), provider, + event_handler, event_logger, parser, audience_matcher) + log = Queue.new + worker = Thread.new do + Thread.current[:signal_parse] = true + Thread.handle_interrupt(Object => :never) do + context.refresh + log << :refresh_completed + end + rescue RuntimeError => e + log << e.message + end + Timeout.timeout(5) { parsing.pop } + worker.raise(RuntimeError, "async") + Timeout.timeout(5) { worker.join } + + expect([log.pop, log.pop]).to eq([:refresh_completed, "async"]) + expect(context.instance_variable_get(:@building_threads)).to be_empty + end + + it "keeps the timeout when it interrupts a refresh waiting to register as a builder" do + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) { OpenStruct.new(data_future: ready_data, success?: true) } + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create(clock, context_config, OpenStruct.new(data_future: data, success?: true), provider, + event_handler, event_logger, variable_parser, audience_matcher) + ready_mutex = context.instance_variable_get(:@ready_mutex) + held = Queue.new + holder = Thread.new { ready_mutex.synchronize { held << true; sleep 0.6 } } + Timeout.timeout(5) { held.pop } + + expect { Timeout.timeout(0.2) { context.refresh } }.to raise_error(Timeout::Error) + Timeout.timeout(5) { holder.join } + expect(context.instance_variable_get(:@building_threads)).to be_empty + end + + it "does not leave a thread registered as a builder when a timeout lands during its cleanup" do + holder = {} + grabbed = Queue.new + parser = DefaultVariableParser.new + parser.define_singleton_method(:parse) do |context, experiment, variant, config| + if Thread.current[:arm] && !Thread.current[:fired] + Thread.current[:fired] = true + mutex = holder[:context].instance_variable_get(:@ready_mutex) + holder[:locker] = Thread.new { mutex.synchronize { grabbed << true; sleep 0.6 } } + grabbed.pop + end + super(context, experiment, variant, config) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, event_handler, event_logger, + parser, audience_matcher) + holder[:context] = context + Thread.current[:arm] = true + begin + Timeout.timeout(0.2) { context.set_data(OpenStruct.new(data_future: data, success?: true)) } + rescue Timeout::Error + nil + ensure + Thread.current[:arm] = nil + Thread.current[:fired] = nil + end + Timeout.timeout(5) { holder[:locker].join } + + expect(context.instance_variable_get(:@building_threads)).to be_empty + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + context.wait_until_ready(0.3) + expect(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).to be >= 0.25 + end + + # The interrupt is queued under a mask from a hook on the first line of + # build_state's cleanup, and is delivered before that line runs: the + # window before any cleanup there could be masked. The same thread then + # waits for readiness, which must block rather than return as a builder, + # or builds again, which must leave it unregistered afterwards. + [[false, false, false], [true, false, false], [false, true, false], [true, true, false], + [false, false, true]].each do |rebuild, in_fiber, nested_wait| + it "does not treat a thread as a builder after an interrupt lands as its build cleanup starts#{rebuild ? " and it builds again" : ""}#{in_fiber ? " in a fiber that then ends" : ""}#{nested_wait ? ", waiting from a nested fiber" : ""}" do + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, event_handler, event_logger, + variable_parser, audience_matcher) + source, first = Context.instance_method(:build_state).source_location + lines = File.readlines(source) + cleanup = (first...lines.size).find { |i| lines[i].strip == "ensure" } + expect(cleanup).not_to be_nil, "build_state no longer has an ensure" + cleanup_line = cleanup + 2 + worker = Thread.new do + me = Thread.current + trace = TracePoint.new(:line) do |tp| + # A thread variable, not a fiber-local: the build may run in a fiber. + next unless tp.path == source && tp.lineno == cleanup_line && me.thread_variable_get(:arm) + + me.thread_variable_set(:arm, false) + Thread.handle_interrupt(Object => :never) { Thread.new { me.raise(RuntimeError, "async") }.join } + end + trace.enable + me.thread_variable_set(:arm, true) + build = lambda do + context.set_data(OpenStruct.new(data_future: data, success?: true)) + :completed + rescue RuntimeError => e + e.message + end + # A build interrupted in a fiber leaves an entry naming that fiber; + # once it has ended, the entry is stale from the thread's own fiber. + outcome = begin + in_fiber ? Fiber.new { build.call }.resume : build.call + ensure + trace.disable + end + waited = nil + if rebuild + context.set_data(OpenStruct.new(data_future: data, success?: true)) + else + # From a nested fiber of the still-alive registering fiber too + # (Ruby 3.0+ can read that fiber's stack; 2.7 cannot). + wait = lambda do + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + context.wait_until_ready(0.3) + Process.clock_gettime(Process::CLOCK_MONOTONIC) - started + end + waited = nested_wait && Fiber.current.respond_to?(:backtrace_locations) ? Fiber.new { wait.call }.resume : wait.call + end + [outcome, waited, context.instance_variable_get(:@building_threads).key?(me)] + end + outcome, waited, still_registered = Timeout.timeout(5) { worker.value } + + expect(outcome).to eq("async") + expect(waited).to be >= 0.25 unless rebuild + expect(still_registered).to be false + end + end + + it "finalize still raises a real rejection when recovery lands as its flush starts" do + refresh_in = Queue.new + refresh_out = Queue.new + ready_data = data + provider = Object.new + provider.define_singleton_method(:context_data) do + refresh_in << true + refresh_out.pop + OpenStruct.new(data_future: ready_data, success?: true) + end + # Only the first send is rejected: finalize must raise it rather than let + # its second pass send the batch and seal. + sends = 0 + handler = Object.new + handler.define_singleton_method(:publish) do |_context, _event| + sends += 1 + sends == 1 ? OpenStruct.new(exception: Exception.new("REJECTED"), success?: false) : OpenStruct.new(success?: true) + end + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, provider, handler, event_logger, + variable_parser, audience_matcher) + refresher = Thread.new { context.refresh } + Timeout.timeout(5) { refresh_in.pop } + context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) + context.track("goal1", nil) + # The context is failed when finalize starts; the refresh recovers just as + # its flush begins, so that flush sends the goal and is rejected. + original = context.method(:flush) + allow(context).to receive(:flush) do |**kwargs| + if kwargs[:sealing] && refresher.alive? + refresh_out << true + Timeout.timeout(5) { refresher.join } + end + original.call(**kwargs) + end + begin + expect(context.failed?).to be true + expect { Timeout.timeout(5) { context.finalize } }.to raise_error(StandardError, "REJECTED") + ensure + refresh_out << true + refresher.join(5) || refresher.kill + end + expect(context.finalized?).to be false + expect(context.pending_count).to eq(1) + end + + it "finalize does not raise the load error when the initial fetch fails during its flush" do + handler = Object.new + handler.define_singleton_method(:publish) { |_context, _event| OpenStruct.new(success?: true) } + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, handler, event_logger, + variable_parser, audience_matcher) + context.track("before", nil) + original = context.method(:flush) + allow(context).to receive(:flush) do |**kwargs| + unless Thread.current[:failed_once] + Thread.current[:failed_once] = true + Thread.new { context.set_data(OpenStruct.new(exception: failure, success?: false, data_future: nil)) }.join(5) + end + original.call(**kwargs) + end + + expect { Timeout.timeout(5) { context.finalize } }.not_to raise_error + expect(context.finalized?).to be true + ensure + Thread.current[:failed_once] = nil + end + + it "wakes a waiter when a refresh supplies the first data" do + context_config = ContextConfig.create + context_config.set_units(units) + context = Context.create_async(clock, context_config, data_provider, + event_handler, event_logger, variable_parser, audience_matcher) + # Signal from the condition-variable wait itself, so the refresh runs only + # once the waiter is really waiting; the waiter has no timeout of its own, + # so only a broadcast can wake it. + waiting = Queue.new + condvar = context.instance_variable_get(:@ready_condvar) + allow(condvar).to receive(:wait).and_wrap_original do |original, *args| + waiting << true + original.call(*args) + end + waiter = Thread.new { context.wait_until_ready } + begin + Timeout.timeout(5) { waiting.pop } + context.refresh + expect(waiter.join(5)).to eq(waiter) + expect(context.ready?).to be true + ensure + waiter.kill if waiter.alive? + end + end end describe "Context#wait_until_ready" do diff --git a/spec/fix_plan_spec.rb b/spec/fix_plan_spec.rb index 2a9a995c..22cb6940 100644 --- a/spec/fix_plan_spec.rb +++ b/spec/fix_plan_spec.rb @@ -33,7 +33,7 @@ let(:data) { descr.deserialize(json, 0, json.length) } let(:publish_future) { OpenStruct.new(success?: true) } let(:event_handler) do - ev = instance_double(ContextPublisher) + ev = instance_double(Absmartly::ContextPublisher) allow(ev).to receive(:publish).and_return(publish_future) ev end @@ -100,7 +100,7 @@ def create_ready_context(evt_handler: nil) end it "flush atomically clears events before publishing" do - ev = instance_double(ContextPublisher) + ev = instance_double(Absmartly::ContextPublisher) allow(ev).to receive(:publish).and_return(publish_future) context = create_ready_context(evt_handler: ev) @@ -316,7 +316,7 @@ def create_ready_context(evt_handler: nil) describe "Fix 1.3: publish error handling preserves events on failure" do it "preserves pending_count after publish failure" do - ev = instance_double(ContextPublisher) + ev = instance_double(Absmartly::ContextPublisher) failure = Exception.new("FAILED") failure_future = OpenStruct.new(exception: failure, success?: false, data_future: nil) allow(ev).to receive(:publish).and_return(failure_future) @@ -353,17 +353,17 @@ def create_ready_context(evt_handler: nil) end end - describe "Fix 4.1: set_override works after context is closed" do - it "allows set_override after close without raising" do + describe "Fix 4.1: set_override works after context is finalized" do + it "allows set_override after finalize without raising" do context = create_ready_context - context.close + context.finalize expect { context.set_override("exp_test_ab", 2) }.not_to raise_error end - it "allows set_overrides after close without raising" do + it "allows set_overrides after finalize without raising" do context = create_ready_context - context.close + context.finalize expect { context.set_overrides("exp_test_ab": 2) }.not_to raise_error end @@ -425,7 +425,7 @@ def create_ready_context(evt_handler: nil) end end - describe "shared variable keys resolve like the JavaScript SDK" do + describe "shared variable keys resolve like java-sdk Context.getVariableAssignment" do def shared_experiment(id, name, unit_type, full_on_variant) { "id" => id, "name" => name, "unitType" => unit_type, @@ -443,7 +443,7 @@ def shared_experiment(id, name, unit_type, full_on_variant) def shared_context(published, exp_a_full_on: 0) json = JSON.generate({ "experiments" => [shared_experiment(1, "exp_a", "user_id", exp_a_full_on), shared_experiment(2, "exp_b", "session_id", 1)] }) - handler = instance_double(ContextPublisher) + handler = instance_double(Absmartly::ContextPublisher) allow(handler).to receive(:publish) { |_ctx, event| published.concat(event.exposures || []); publish_future } config = ContextConfig.create config.set_unit(:session_id, "test-unit") @@ -461,7 +461,7 @@ def shared_context(published, exp_a_full_on: 0) expect(published.map(&:name)).to eq(%w[exp_a]) end - it "falls through to the next experiment when the unit isn't assigned in the first" do + it "reads from and exposes only the next experiment when the unit isn't assigned in the first" do published = [] context = shared_context(published) @@ -469,7 +469,7 @@ def shared_context(published, exp_a_full_on: 0) expect(context.pending_count).to eq(0) expect(context.variable_value("shared.key", "default")).to eq("from_exp_b") context.publish - expect(published.map { |e| [e.name, e.assigned] }).to eq([["exp_a", false], ["exp_b", true]]) + expect(published.map { |e| [e.name, e.assigned] }).to eq([["exp_b", true]]) end it "reads from an experiment the unit is overridden in" do @@ -479,13 +479,13 @@ def shared_context(published, exp_a_full_on: 0) expect(context.peek_variable_value("shared.key", "default")).to eq("from_exp_a") end - it "falls through when the assigned variant's config lacks the key" do + it "gives the default, not a later experiment's value, when the winner's variant lacks the key" do exp_a = shared_experiment(1, "exp_a", "session_id", 1) exp_a["variants"] = [{ "name" => "A", "config" => %({"other.key":"from_exp_a"}) }, { "name" => "B", "config" => %({"shared.key":"from_exp_a"}) }] json = JSON.generate({ "experiments" => [exp_a, shared_experiment(2, "exp_b", "session_id", 1)] }) published = [] - handler = instance_double(ContextPublisher) + handler = instance_double(Absmartly::ContextPublisher) allow(handler).to receive(:publish) { |_ctx, event| published.concat(event.exposures || []); publish_future } config = ContextConfig.create config.set_unit(:session_id, "test-unit") @@ -494,17 +494,17 @@ def shared_context(published, exp_a_full_on: 0) variable_parser, audience_matcher) context.set_override("exp_a", 0) - expect(context.peek_variable_value("shared.key", "default")).to eq("from_exp_b") - expect(context.variable_value("shared.key", "default")).to eq("from_exp_b") + expect(context.peek_variable_value("shared.key", "default")).to eq("default") + expect(context.variable_value("shared.key", "default")).to eq("default") context.publish - expect(published.map(&:name)).to eq(%w[exp_a exp_b]) + expect(published.map(&:name)).to eq(%w[exp_a]) end it "orders experiments by id, not payload order" do json = JSON.generate({ "experiments" => [shared_experiment(2, "exp_b", "session_id", 1), shared_experiment(1, "exp_a", "session_id", 1)] }) published = [] - handler = instance_double(ContextPublisher) + handler = instance_double(Absmartly::ContextPublisher) allow(handler).to receive(:publish) { |_ctx, event| published.concat(event.exposures || []); publish_future } config = ContextConfig.create config.set_unit(:session_id, "test-unit") diff --git a/spec/hashing_spec.rb b/spec/hashing_spec.rb index 56356306..8630befd 100644 --- a/spec/hashing_spec.rb +++ b/spec/hashing_spec.rb @@ -37,10 +37,13 @@ end end - it "hashes numbers as their value rounded to an integer" do + it "hashes numbers from their to_s text, as in v1.3.0" do expect(Hashing.hash_unit(12345)).to eq("gnzLDuqKcGxMNKFokfhOew") expect(Hashing.hash_unit(125)).to eq("Pe8YStj0dV_yaYYup3OT3Q") - expect(Hashing.hash_unit(125.75)).to eq("BpBZt--EDwx0qBTskje27A") + # 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") end it "hashes integers by their exact decimal text, like v1.3.0" do @@ -64,15 +67,6 @@ end expect(Hashing.hash_unit(BigDecimal("123"))).to eq(Hashing.hash_unit("0.123e3")) end - - it "formats numbers like JavaScript toFixed(0)" do - expect(Hashing.hash_unit(-0.1)).to eq("815ubasUW2p7sFI440lKaw") - expect(Hashing.hash_unit(1e21)).to eq("OKkjo8sn5USSUjdjCUBynw") - { -0.1 => "-0", -0.0 => "0", -2.5 => "-3", 2.5 => "3", 1e21 => "1e+21", 1.5e22 => "1.5e+22", - 1e20 => "100000000000000000000", 2**60 + 1 => "1152921504606846976" }.each do |num, text| - expect(Hashing.number_to_fixed0(num)).to eq(text) - end - end end describe ".base64_url_no_padding" do diff --git a/spec/json_expr/semver_comparator_spec.rb b/spec/json_expr/semver_comparator_spec.rb index a1eae5ea..0e6d7fe2 100644 --- a/spec/json_expr/semver_comparator_spec.rb +++ b/spec/json_expr/semver_comparator_spec.rb @@ -3,7 +3,7 @@ require "json_expr/json_expr" require "json_expr/semver_comparator" -RSpec.describe SemverComparator do +RSpec.describe Absmartly::SemverComparator do let(:json_expr) { JsonExpr.new } let(:evaluator) { ExprEvaluator.new(json_expr.operators, {}) } diff --git a/spec/local_server_integration_spec.rb b/spec/local_server_integration_spec.rb index 7bb3f884..9f8417ed 100644 --- a/spec/local_server_integration_spec.rb +++ b/spec/local_server_integration_spec.rb @@ -137,7 +137,7 @@ def stop expect(body["goals"].first["name"]).to eq("payment") end - it "raises a StandardError-catchable publish failure on a real 503, stays open, and retries" do + it "finalize raises a StandardError-catchable publish failure on a real 503, stays open, and retries" do server.put_status = 503 sdk = ABSmartly.new( @@ -158,33 +158,39 @@ def stop # `rescue StandardError`, not Ruby's base Exception. raised = nil begin - context.close + context.finalize rescue StandardError => e raised = e end expect(raised).to be_a(StandardError) expect(context.closed?).to be(false) + expect(context.finalized?).to be(false) expect(context.finalizing?).to be(false) expect(context.pending_count).to eq(1) server.put_status = 200 - expect(context.close).to be_nil - expect(context.closed?).to be(true) + expect(context.finalize).to be_nil + expect(context.finalized?).to be(true) expect(context.pending_count).to eq(0) puts = server.requests.count { |r| r[:method] == "PUT" } expect(puts).to eq(2) end - it "finalize raises a StandardError-catchable publish failure on a real 503" do + it "close logs a real 503, drops that batch and seals without raising, as in 1.3.0" do server.put_status = 503 + errors = [] + logger = Class.new(ContextEventLogger) do + define_method(:handle_event) { |event, data| errors << data if event == ContextEventLogger::EVENT_TYPE::ERROR } + end.new sdk = ABSmartly.new( server.base_url, api_key: "test-api-key", application: "website", - environment: "dev" + environment: "dev", + context_event_logger: logger ) context_config = ContextConfig.create @@ -194,15 +200,13 @@ def stop context.wait_until_ready context.track("payment", { value: 99 }) - raised = nil - begin - context.finalize - rescue StandardError => e - raised = e - end + expect { context.close }.not_to raise_error + expect(context.closed?).to be(true) + expect(context.pending_count).to eq(0) + expect(errors.size).to eq(1) - expect(raised).to be_a(StandardError) - expect(context.closed?).to be(false) - expect(context.pending_count).to eq(1) + puts = server.requests.select { |r| r[:method] == "PUT" } + expect(puts.size).to eq(1) + expect(JSON.parse(puts.first[:body])["goals"].map { |g| g["name"] }).to eq(["payment"]) end end diff --git a/spec/parity_spec.rb b/spec/parity_spec.rb index 7899604c..a713589d 100644 --- a/spec/parity_spec.rb +++ b/spec/parity_spec.rb @@ -37,23 +37,27 @@ expect(Hashing.hash_unit(value)).to eq(hash) end - 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) + it "normalizes #{value.inspect} to the same UTF-8 from UTF-16 and from CESU-8 bytes" do + expect(Hashing.to_utf8(value.encode("UTF-16LE")).bytes).to eq(bytes) 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) + 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))) 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.hash_unit(wtf8)).to eq(lone_surrogate_hash) + expect(Hashing.base64_url_no_padding(Digest::MD5.digest(Hashing.to_utf8(wtf8).b))).to eq(lone_surrogate_hash) end it "replaces other invalid bytes with U+FFFD" do @@ -110,7 +114,7 @@ def value(x) let(:failure_future) { OpenStruct.new(exception: failure, success?: false, data_future: nil) } let(:ok_future) { OpenStruct.new(success?: true) } let(:data_provider) { instance_double(ContextDataProvider, context_data: ready_future) } - let(:handler) { instance_double(ContextPublisher) } + let(:handler) { instance_double(Absmartly::ContextPublisher) } let(:events) { [] } let(:logger) do log = events @@ -126,24 +130,24 @@ def make_context(future = ready_future, event_logger: logger) DefaultVariableParser.new, AudienceMatcher.new(DefaultAudienceDeserializer.new)) end - it "keeps the context open and the events queued when the final publish fails" do + it "finalize keeps the context open and the events queued when the final publish fails" do allow(handler).to receive(:publish).and_return(failure_future) context = make_context context.track("goal1", nil) - expect { context.close }.to raise_error(failure) + expect { context.finalize }.to raise_error(StandardError, failure.message) { |error| expect(error.cause).to eq(failure) } expect(context.closed?).to be(false) expect(context.finalizing?).to be(false) expect(context.pending_count).to eq(1) - expect(events.map(&:first)).not_to include(ContextEventLogger::EVENT_TYPE::CLOSE) + expect(events.map(&:first)).not_to include(ContextEventLogger::EVENT_TYPE::FINALIZE) allow(handler).to receive(:publish).and_return(ok_future) - expect(context.close).to be_nil + expect(context.finalize).to be_nil expect(context.closed?).to be(true) expect(context.pending_count).to eq(0) expect(handler).to have_received(:publish).twice - expect(events.map(&:first)).to include(ContextEventLogger::EVENT_TYPE::CLOSE) + expect(events.map(&:first)).to include(ContextEventLogger::EVENT_TYPE::FINALIZE) end it "emits the finalize event under the name \"finalize\" from finalize" do @@ -179,7 +183,7 @@ def make_context(future = ready_future, event_logger: logger) it "keeps a ready context usable after a failed refresh" do context = make_context allow(data_provider).to receive(:context_data).and_return(failure_future) - expect(context.refresh).to eq(failure) + context.refresh expect(context.failed?).to be(false) expect(context.experiments).to eq(data.experiments.map(&:name)) end @@ -211,13 +215,12 @@ def handle_event(_event, _data) expect(context.pending_count).to eq(1) end - it "normalizes a unit to UTF-8 before comparing and hashing it" do + it "keeps a unit in its own encoding, as in v1.3.0" do config = ContextConfig.create context = Context.create(clock, config, ready_future, data_provider, handler, logger, DefaultVariableParser.new, AudienceMatcher.new(DefaultAudienceDeserializer.new)) context.set_unit(:user_id, "user\u{1F600}id".encode("UTF-16LE")) - expect(context.get_unit(:user_id).encoding).to eq(Encoding::UTF_8) - expect { context.set_unit(:user_id, "user\u{1F600}id") }.not_to raise_error + expect(context.get_unit(:user_id).encoding).to eq(Encoding::UTF_16LE) end end diff --git a/spec/system_attributes_spec.rb b/spec/system_attributes_spec.rb index b673a94e..96190bb0 100644 --- a/spec/system_attributes_spec.rb +++ b/spec/system_attributes_spec.rb @@ -34,7 +34,7 @@ let(:publish_future) { OpenStruct.new(success?: true) } let(:event_handler) do - ev = double("ContextPublisher") + ev = double("Absmartly::ContextPublisher") allow(ev).to receive(:publish).and_return(publish_future) ev end @@ -303,4 +303,29 @@ def build_sdk(provider:, handler:) expect(context.peek_treatment("exp_env")).to eq(1) expect(context.peek_treatment("exp_app")).to eq(1) end + + it "reads the application and environment from a real Client on every creation path" do + client_config = ClientConfig.new + client_config.endpoint = "https://localhost/v1" + client_config.api_key = "key" + client_config.application = "website" + client_config.environment = "production" + http_client = instance_double(HttpClient) + allow(http_client).to receive(:get) + .and_return(DefaultHttpClient.default_response(200, "OK", "application/json", json)) + config = ABSmartlyConfig.create + config.client = Client.new(client_config, http_client) + sdk = ABSmartly.create(config) + context_config = ContextConfig.create + context_config.set_unit(:session_id, "e791e240fcd3df7d238cfc285f475e8152fcc0ec") + + contexts = { + create_context: sdk.create_context(context_config), + create_context_with: sdk.create_context_with(context_config, data_result), + create_context_async: sdk.create_context_async(context_config).wait_until_ready(5) + } + contexts.each do |path, context| + expect([path, context.peek_treatment("exp_env"), context.peek_treatment("exp_app")]).to eq([path, 1, 1]) + end + end end