diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7ca7fc2..d3389f4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -58,3 +58,27 @@ jobs: test "$installed" = "./bin/app" grep -q 'set(CPACK_PACKAGE_NAME "embedding-app")' "$dir/CPackConfig.cmake" grep -q 'set(CPACK_GENERATOR "TGZ")' "$dir/CPackConfig.cmake" + + sanitizers: + name: Test with ASan and UBSan + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install dependencies + run: | + sudo apt-get update + sudo apt-get install -y cmake g++ libcurl4-openssl-dev + + - name: Configure + run: >- + cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DABSMARTLY_BUILD_TESTS=ON + -DCMAKE_CXX_FLAGS="-fsanitize=address,undefined -fno-sanitize-recover=all -fno-omit-frame-pointer" + + - name: Build + run: cmake --build build --parallel --target absmartly_tests + + - name: Test + run: build/tests/absmartly_tests diff --git a/CHANGELOG.md b/CHANGELOG.md index e3074ca..7e16d07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,78 @@ # Changelog +## 1.1.0 (unreleased) + +### Added + +- Holdouts (`ContextData::holdouts`, `HoldoutData`, `ExperimentData::holdoutIds` + and `ExperimentData::holdoutType`, all new fields appended last and empty by + default). An experiment covered by a holdout that holds the unit out + (arm 0, or arm 1 of a three-arm holdout for an experiment that is not + full-on) returns variant 0 with control variables and publishes no exposure + of its own; each covering holdout publishes one ordinary exposure per unit + type. Overrides and matching assignment rules win over a holdout. Payloads + without holdouts assign and publish exactly as before. A holdout arm is + chosen with javascript-sdk's probability scale, so a unit whose hash lands + exactly on a split boundary gets the same arm in every SDK. Ports + javascript-sdk#65 and java-sdk#12. +- Shared variable keys with holdouts, as in java-sdk: a held-out candidate + never wins a key over a candidate the unit is in; when no candidate wins, the + first held-out candidate supplies its control value (or the caller default + if its variant lacks the key). `variable_value()` publishes the holdout + exposures of every candidate it checks, and the winner's own exposure only + when the winner is not held out. `peek_variable_value()` publishes nothing. +- `contains` operator, an alias of `in`, so the app can start sending + `contains`. The C++ evaluator has registered `contains` as the same + operator as `in` (haystack first, then needle) since 1.0.0; 1.1.0 documents + it and tests every `in` case through both names. `in` is unchanged. +- `ClientConfig::application_version`: the application version sent as + `X-Application-Version`. A whole number of 1 to 18 digits is sent as-is; + anything else (such as `2.4.1`) is sent as `0`, as in java-sdk and + javascript-sdk. `ClientConfig` keeps its 1.0.0 four-element + structured-binding shape. + +### Fixed + +- **`X-Application-Version` was always `0`.** Every 1.0.x client sent + `X-Application-Version: 0` on context fetches and publishes, and there was no + option to set it, so the collector could not attribute events to an + application version. This affects every C++ SDK user who reports on or + targets application versions; set `ClientConfig::application_version` to + send yours. Clients that leave it empty still send `0`. + +### Notes + +- New fields grow the public model and `Context` layouts; rebuild everything + that includes the SDK headers when upgrading (see Installed Package in the + README). `ContextData` and `ExperimentData` keep their 1.0.0 + structured-binding shapes (1 and 19 elements); reach `holdouts`, + `holdoutIds` and `holdoutType` by name. A type derived from either one has + no such shape: a structured binding of it now binds every member (2 and 21 + names). The same holds for `ClientConfig` (4 elements; `application_version` + by name). Code that aggregate-initializes `ExperimentData`, `ContextData` or + `ClientConfig` positionally still compiles, but `-Wextra` reports the + appended fields as missing initializers. + +- Cached reads cost the same as in 1.0.1 or less. Measured with GCC 15.2 on + aarch64 with 50 experiments and no holdouts, other paths are slower: the + first resolution of each experiment by about 2-3% (first `peek()` 295 to + 304 ns, first `treatment()` 2,168 to 2,184 ns, with the same allocation + count), partly from the 24-byte larger cached assignment and partly from + the holdout checks; and `refresh()` by about 12% (112 to 126 us, 151 more + allocations), because it copies the new payload into fresh storage before + installing it (see below). + +- `refresh()` copies and indexes the new payload before installing it, so a + `std::bad_alloc` while doing so leaves the previous data installed and + readable. As in 1.0.1, an allocation failure inside a nlohmann/json + destructor during that copy still terminates the process. + +- All exposures of one `treatment()` call on a covered experiment, and of one + `variable_value()` call (its holdouts' and the winner's), are queued before + the event logger sees the first of them, so a logger that calls `finalize()` + or `publish()` from that callback sends them all, as javascript-sdk 1.14 + does. + ## 1.0.1 (2026-11-27) ### Fixed diff --git a/CMakeLists.txt b/CMakeLists.txt index 826fd0d..47d553c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.16) -project(absmartly-sdk VERSION 1.0.1 LANGUAGES CXX) +project(absmartly-sdk VERSION 1.1.0 LANGUAGES CXX) include(FetchContent) include(GNUInstallDirs) diff --git a/README.md b/README.md index 80763f0..c847ea3 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,16 @@ find_package(absmartly-sdk 1.0 REQUIRED) target_link_libraries(your_target PRIVATE absmartly::absmartly-sdk) ``` +The package's version check (`SameMajorVersion`) selects a package with the +same major version; it is not a binary-compatibility guarantee. Public types +such as `ContextData`, `ExperimentData` and `Context` gain fields in 1.1.0. +Existing positional initializers remain valid, and `ContextData` and +`ExperimentData` keep their 1.0.0 structured-binding shapes (`auto& +[experiments] = data`, and the 19 released `ExperimentData` members); access +the new holdout fields by name. The binary layout changes, so rebuild +your application and every library that includes the SDK headers against the +SDK version you link. Do not mix objects compiled against different SDK versions. + ## Getting Started Please follow the [installation](#installation) instructions before trying the following code. @@ -85,6 +95,7 @@ int main() { client_config.api_key = "YOUR_API_KEY"; client_config.application = "website"; client_config.environment = "production"; + client_config.application_version = "100204"; // optional, sent as X-Application-Version auto sdk = absmartly::SDK::create_simple(client_config); absmartly::ContextConfig ctx_config; @@ -97,6 +108,10 @@ int main() { } ``` +`application_version` is sent as `X-Application-Version` with every request. +The collector reads it as a whole number, so only 1 to 18 digits are sent +as-is; anything else, such as `"2.4.1"`, or no version, is sent as `0`. + #### Alternative: Using Configuration Objects For use cases with custom HTTP clients or providers: @@ -426,6 +441,59 @@ later rules are not tried. Rules that are malformed in any other way are skipped. Rule-assigned exposures are flagged `ruleOverride` so the backend can exclude them from analysis. +### Holdouts + +A holdout keeps a share of your units out of a group of experiments, so you can +measure the combined effect of everything the group ships. Holdouts are set up +in the Web Console and arrive with the context data +(`ContextData::holdouts`); each experiment lists the holdouts covering it in +`ExperimentData::holdoutIds`. There is nothing to call: `treatment()`, +`peek()`, `variable_value()` and `peek_variable_value()` apply them. + +- The unit is randomised into one of the holdout's arms with the covered + experiment's unit type. Arm 0 holds the unit out. A holdout with three arms + (a three-way split) also holds the unit out at arm 1, but only of covered + experiments that are not full-on; full-on experiments keep their full-on + variant there. Any other arm leaves the experiment to its normal assignment. +- A unit held out by any one of an experiment's holdouts gets variant 0, and + the experiment publishes no exposure of its own. A holdout beats audience + targeting, full-on and custom assignments. `set_override()` and a matching + assignment rule still win over it. +- For a variable key (see Shared variable keys), a held-out experiment never + wins over one the unit is assigned to, overridden or rule-assigned in. When + no candidate wins, the first held-out candidate supplies its control value, + or your default if its control variant lacks the key. +- The first `treatment()` on a covered experiment also publishes one exposure + for each covering holdout (its id, name and arm), once per holdout and unit + type. `variable_value()` does so for every candidate it checks for the key, + as the Java SDK does, while still exposing only the winning experiment. + `peek()` and `peek_variable_value()` publish nothing. +- The arm is kept until the holdout's iteration changes; other edits to the + holdout do not re-randomise the unit. +- Set the unit of each covered experiment's unit type before the first + `treatment()` or `variable_value()` on it. Without the unit the holdout + cannot be evaluated, and an experiment already exposed that way keeps its + decision (so it never publishes a second, conflicting exposure). A `peek()` + or `peek_variable_value()` before the unit is set is fine: the decision is + made again once the unit arrives. + +Holdout ids are integers on the wire. A holdout id sent as a string (`"11"`) +is ignored here, whereas javascript-sdk coerces it; the Collector never sends +one. Likewise a holdout without a `name` publishes its exposure with an empty +name, where javascript-sdk leaves the name out. + +Payloads without holdouts behave exactly as before. + +### Containment Operators + +`in` and its alias `contains` take the haystack first, then the needle: a list +contains an equal element, a string contains a substring, and an object +contains a key. A null haystack or needle gives no match. + +```cpp +// {"contains": [{"var": "tags"}, {"value": "beta"}]} matches tags ["beta", "pro"] +``` + ### Semantic Version Operators Audience filters and rule conditions can compare versions with `semver_eq`, diff --git a/include/absmartly/client_config.h b/include/absmartly/client_config.h index 927a03b..7833e82 100644 --- a/include/absmartly/client_config.h +++ b/include/absmartly/client_config.h @@ -1,6 +1,9 @@ #pragma once +#include #include +#include +#include namespace absmartly { @@ -9,6 +12,48 @@ struct ClientConfig { std::string api_key; std::string application; std::string environment; + // Sent as X-Application-Version. The collector reads it as a 64-bit integer, so only a + // whole number of 1 to 18 digits (surrounding whitespace ignored) is sent; anything else, + // such as "2.4.1", or no version at all, is sent as "0". + std::string application_version; }; +// Keep the four-element structured-binding shape published in 1.0.0. application_version +// is reached by name. +template +decltype(auto) get(ClientConfig& config) noexcept { + static_assert(I < 4, "ClientConfig has four structured-binding elements"); + if constexpr (I == 0) return (config.endpoint); + else if constexpr (I == 1) return (config.api_key); + else if constexpr (I == 2) return (config.application); + else return (config.environment); +} + +template +decltype(auto) get(const ClientConfig& config) noexcept { + return static_cast(get(const_cast(config))); +} + +template +decltype(auto) get(ClientConfig&& config) noexcept { + return static_cast(get(config)); +} + +template +decltype(auto) get(const ClientConfig&& config) noexcept { + return static_cast(get(const_cast(config))); +} + } // namespace absmartly + +namespace std { + +template <> +struct tuple_size : integral_constant {}; + +template +struct tuple_element { + using type = string; +}; + +} // namespace std diff --git a/include/absmartly/context.h b/include/absmartly/context.h index 549b8dd..bbcf59b 100644 --- a/include/absmartly/context.h +++ b/include/absmartly/context.h @@ -20,6 +20,27 @@ namespace absmartly { +// A unit's arm in one holdout, cached per (holdout id, unit type) while the +// holdout's iteration is unchanged. The arm count is pinned with the arm: arm 1 +// means something else in a 2-arm and a 3-arm holdout. +struct HoldoutAssignment { + int id = 0; + int iteration = 0; + std::string unit_type; + int variant = 0; + size_t arm_count = 0; + bool exposed = false; +}; + +// A holdout covering an experiment, as it was when the assignment was resolved. +// `assignment` is null when the experiment's unit was missing. +struct HoldoutPin { + int id = 0; + int iteration = 0; + std::string name; + std::shared_ptr assignment; +}; + struct Assignment { int id = 0; int iteration = 0; @@ -50,6 +71,10 @@ struct Assignment { std::map variables; bool has_variables = false; int attrs_seq = 0; + bool suppressed = false; + // The holdouts covering the experiment when this was resolved, in id order; + // null when there are none. Exposures fire from these, never re-resolved. + std::shared_ptr> holdouts; }; struct ExperimentIndex { @@ -57,6 +82,7 @@ struct ExperimentIndex { std::vector> variables; // data->assignmentRules parsed once; null when there are none or they are invalid. nlohmann::json assignment_rules; + std::vector holdouts; // Sorted by id, unique; non-owning, like data. }; struct RuleResolution { @@ -132,11 +158,23 @@ class Context { // changes only CPU cost. friend struct ContextTestAccess; - Assignment& get_or_create_assignment(const std::string& experiment_name); - std::pair variable_assignment(const std::string& key); + // A supplied index must belong to the live data generation; all validation still runs. + Assignment& get_or_create_assignment(const std::string& experiment_name, const ExperimentIndex* experiment = nullptr); + std::pair variable_assignment(const std::string& key, + std::vector* holdout_events); void queue_exposure(const std::string& experiment_name, const Assignment& assignment); + void trigger_exposures(const std::string& experiment_name, const Assignment& assignment); + nlohmann::json enqueue_exposure(const std::string& experiment_name, const Assignment& assignment); + void enqueue_holdout_exposures(const std::vector& holdouts, std::vector& events); + std::shared_ptr get_holdout_assignment(const HoldoutData& holdout, const std::string& unit_type); + static bool holdouts_match(const ExperimentIndex& experiment, const Assignment& assignment); void build_index(); + // Indexes data into the given maps (pointers into data) and collects variant parse errors; + // touches no member, so a throw leaves the context unchanged. + static void index_data(const ContextData& data, std::map& index, + std::map>& index_variables, + std::vector& errors); bool experiment_matches(const ExperimentData& experiment, const Assignment& assignment) const; bool audience_matches(const ExperimentData& experiment, Assignment& assignment); @@ -198,6 +236,13 @@ class Context { std::future data_future_; AudienceMatcher audience_matcher_; + + // Kept across refreshes so a holdout exposure fires once per (id, unit type) and iteration. + std::map, std::shared_ptr> holdout_assignments_; + + // Variable reads that reused their candidate's index entry instead of looking the name up. + unsigned long long index_reuses_ = 0; + }; } // namespace absmartly diff --git a/include/absmartly/models.h b/include/absmartly/models.h index e09a8b9..6f5c926 100644 --- a/include/absmartly/models.h +++ b/include/absmartly/models.h @@ -1,10 +1,15 @@ #pragma once #include +#include +#include +#include #include #include #include #include #include +#include +#include namespace absmartly { @@ -69,8 +74,82 @@ struct ExperimentData { // JSON string of ordered assignment rules ({"rules": [...]}); empty when the // experiment has none. A value sent as anything but a string is ignored. std::string assignmentRules; + // Ids of the holdouts covering this experiment, resolved against + // ContextData::holdouts; an id with no usable holdout is ignored. + std::vector holdoutIds; + // Carried for wire fidelity only: a holdout's arm count comes from its split. + std::string holdoutType; }; +namespace detail { +// The 19 members ExperimentData had in 1.0.0, in order, for its structured bindings. +template +decltype(auto) experiment_member(E& e) noexcept { + static_assert(I < 19, "ExperimentData has 19 structured-binding elements"); + if constexpr (I == 0) { + return (e.id); + } else if constexpr (I == 1) { + return (e.name); + } else if constexpr (I == 2) { + return (e.unitType); + } else if constexpr (I == 3) { + return (e.iteration); + } else if constexpr (I == 4) { + return (e.seedHi); + } else if constexpr (I == 5) { + return (e.seedLo); + } else if constexpr (I == 6) { + return (e.split); + } else if constexpr (I == 7) { + return (e.seedStrictMode); + } else if constexpr (I == 8) { + return (e.trafficSeedHi); + } else if constexpr (I == 9) { + return (e.trafficSeedLo); + } else if constexpr (I == 10) { + return (e.trafficSplit); + } else if constexpr (I == 11) { + return (e.fullOnVariant); + } else if constexpr (I == 12) { + return (e.audience); + } else if constexpr (I == 13) { + return (e.variants); + } else if constexpr (I == 14) { + return (e.audienceStrict); + } else if constexpr (I == 15) { + return (e.customFieldValues); + } else if constexpr (I == 16) { + return (e.application); + } else if constexpr (I == 17) { + return (e.environment); + } else if constexpr (I == 18) { + return (e.assignmentRules); + } +} +} // namespace detail + +// Keep the 19-element structured-binding shape published in 1.0.0; holdoutIds and +// holdoutType are reached by name. +template +decltype(auto) get(ExperimentData& e) noexcept { + return detail::experiment_member(e); +} + +template +decltype(auto) get(const ExperimentData& e) noexcept { + return detail::experiment_member(e); +} + +template +decltype(auto) get(ExperimentData&& e) noexcept { + return std::move(detail::experiment_member(e)); +} + +template +decltype(auto) get(const ExperimentData&& e) noexcept { + return std::move(detail::experiment_member(e)); +} + inline void to_json(nlohmann::json& j, const ExperimentData& e) { j = nlohmann::json{ {"id", e.id}, @@ -95,8 +174,72 @@ inline void to_json(nlohmann::json& j, const ExperimentData& e) { if (!e.assignmentRules.empty()) { j["assignmentRules"] = e.assignmentRules; } + if (!e.holdoutIds.empty()) { + j["holdoutIds"] = e.holdoutIds; + } + if (!e.holdoutType.empty()) { + j["holdoutType"] = e.holdoutType; + } +} + +namespace detail { + +// A JSON integer (or integral float) that fits an int, as JS reads a holdout id. +inline bool get_int(const nlohmann::json& j, int& out) { + if (j.is_number_integer()) { + if (j.is_number_unsigned()) { + const auto value = j.get(); + if (value > static_cast(INT32_MAX)) return false; + out = static_cast(value); + return true; + } + const auto value = j.get(); + if (value < INT32_MIN || value > INT32_MAX) return false; + out = static_cast(value); + return true; + } + if (j.is_number_float()) { + const double value = j.get(); + if (!(value >= INT32_MIN && value <= INT32_MAX) || + std::islessgreater(static_cast(static_cast(value)), value)) { + return false; + } + out = static_cast(value); + return true; + } + return false; +} + +// A seed as JS reads it (ECMAScript ToInt32 of a JSON number, which JS holds as a +// double): truncated toward zero and wrapped to 32 bits, so 4294967297 reads as 1 +// and 1e20 as 1661992960. +inline int32_t to_int32(double d) { + if (!std::isfinite(d)) return 0; + double wrapped = std::fmod(std::trunc(d), 4294967296.0); + if (wrapped < 0) wrapped += 4294967296.0; + return static_cast(static_cast(wrapped)); +} + +inline bool get_seed(const nlohmann::json& j, int32_t& out) { + if (!j.is_number()) return false; + // Exact for integers within 2^53; larger ones round to a double first, as in JS. + if (j.is_number_unsigned()) { + const auto value = j.get(); + out = value <= (1ULL << 53) ? static_cast(static_cast(value)) + : to_int32(static_cast(value)); + } else if (j.is_number_integer()) { + const auto value = j.get(); + out = (value <= (1LL << 53) && value >= -(1LL << 53)) + ? static_cast(static_cast(static_cast(value))) + : to_int32(static_cast(value)); + } else { + out = to_int32(j.get()); + } + return true; } +} // namespace detail + inline void from_json(const nlohmann::json& j, ExperimentData& e) { j.at("id").get_to(e.id); j.at("name").get_to(e.name); @@ -148,18 +291,137 @@ inline void from_json(const nlohmann::json& j, ExperimentData& e) { if (j.contains("assignmentRules") && j["assignmentRules"].is_string()) { j.at("assignmentRules").get_to(e.assignmentRules); } + // Coverage is replaced on every decode, so a model decoded again from a payload without + // holdouts never keeps stale coverage (unlike the older optional fields). + e.holdoutIds.clear(); + e.holdoutType.clear(); + if (j.contains("holdoutIds") && j["holdoutIds"].is_array()) { + for (const auto& id : j["holdoutIds"]) { + int value = 0; + if (detail::get_int(id, value)) { + e.holdoutIds.push_back(value); + } + } + } + if (j.contains("holdoutType") && j["holdoutType"].is_string()) { + j.at("holdoutType").get_to(e.holdoutType); + } +} + +// A holdout: a randomisation over the units of the experiments that list its id +// in holdoutIds. Arm 0 holds the unit out of every covered experiment; in a +// 3-arm holdout, arm 1 holds it out of covered experiments that are not full-on. +struct HoldoutData { + int id = 0; + std::string name; + std::string unitType; + int iteration = 0; + int32_t seedHi = 0; + int32_t seedLo = 0; + std::vector split; + std::string holdoutType; +}; + +inline void to_json(nlohmann::json& j, const HoldoutData& h) { + j = nlohmann::json{ + {"id", h.id}, + {"name", h.name}, + {"unitType", h.unitType}, + {"iteration", h.iteration}, + {"seedHi", h.seedHi}, + {"seedLo", h.seedLo}, + {"split", h.split} + }; + if (!h.holdoutType.empty()) { + j["holdoutType"] = h.holdoutType; + } +} + +// Only the id is required; other fields keep their defaults when absent, of +// another type or out of range, and unknown fields are ignored. A missing name +// publishes "" (the Collector always sends one). +inline void from_json(const nlohmann::json& j, HoldoutData& h) { + if (!j.is_object() || !j.contains("id") || !detail::get_int(j["id"], h.id)) { + throw nlohmann::json::type_error::create(302, "holdout without an integer id", &j); + } + if (j.contains("name") && j["name"].is_string()) { + j.at("name").get_to(h.name); + } + if (j.contains("unitType") && j["unitType"].is_string()) { + j.at("unitType").get_to(h.unitType); + } + if (j.contains("iteration")) { + detail::get_int(j["iteration"], h.iteration); + } + if (j.contains("seedHi")) { + detail::get_seed(j["seedHi"], h.seedHi); + } + if (j.contains("seedLo")) { + detail::get_seed(j["seedLo"], h.seedLo); + } + if (j.contains("split") && j["split"].is_array()) { + const auto& split = j["split"]; + if (std::all_of(split.begin(), split.end(), [](const nlohmann::json& v) { return v.is_number(); })) { + split.get_to(h.split); + } + } + if (j.contains("holdoutType") && j["holdoutType"].is_string()) { + j.at("holdoutType").get_to(h.holdoutType); + } } struct ContextData { std::vector experiments; + std::vector holdouts; }; +// Keep the one-element structured-binding shape published in 1.0.0. New fields remain +// available by name without changing existing `auto& [experiments] = data` consumers. +template +decltype(auto) get(ContextData& data) noexcept { + static_assert(I == 0, "ContextData has one structured-binding element"); + return (data.experiments); +} + +template +decltype(auto) get(const ContextData& data) noexcept { + static_assert(I == 0, "ContextData has one structured-binding element"); + return (data.experiments); +} + +template +decltype(auto) get(ContextData&& data) noexcept { + static_assert(I == 0, "ContextData has one structured-binding element"); + return std::move(data.experiments); +} + +template +decltype(auto) get(const ContextData&& data) noexcept { + static_assert(I == 0, "ContextData has one structured-binding element"); + return std::move(data.experiments); +} + inline void to_json(nlohmann::json& j, const ContextData& c) { j = nlohmann::json{{"experiments", c.experiments}}; + if (!c.holdouts.empty()) { + j["holdouts"] = c.holdouts; + } } inline void from_json(const nlohmann::json& j, ContextData& c) { j.at("experiments").get_to(c.experiments); + c.holdouts.clear(); + if (j.contains("holdouts") && j["holdouts"].is_array()) { + for (const auto& entry : j["holdouts"]) { + if (!entry.is_object()) { + continue; + } + try { + c.holdouts.push_back(entry.get()); + } catch (const nlohmann::json::exception&) { + } + } + } } struct Exposure { @@ -291,3 +553,23 @@ inline void from_json(const nlohmann::json& j, PublishEvent& p) { } } // namespace absmartly + +namespace std { + +template <> +struct tuple_size : integral_constant {}; + +template +struct tuple_element { + using type = remove_reference_t(declval()))>; +}; + +template <> +struct tuple_size : integral_constant {}; + +template <> +struct tuple_element<0, absmartly::ContextData> { + using type = vector; +}; + +} // namespace std diff --git a/include/absmartly/variant_assigner.h b/include/absmartly/variant_assigner.h index eb22db8..25e8b37 100644 --- a/include/absmartly/variant_assigner.h +++ b/include/absmartly/variant_assigner.h @@ -9,8 +9,13 @@ class VariantAssigner { public: explicit VariantAssigner(const std::string& hashed_unit); int assign(const std::vector& split, int32_t seed_hi, int32_t seed_lo) const; + // As javascript-sdk and java-sdk: the hash scaled by 1/0xffffffff, so a hash can land + // exactly on a split boundary. Used for holdouts; experiments keep assign()'s scale. + int assign_holdout(const std::vector& split, int32_t seed_hi, int32_t seed_lo) const; private: + uint32_t hash(int32_t seed_hi, int32_t seed_lo) const; + uint32_t unit_hash_; }; diff --git a/src/client.cpp b/src/client.cpp index 4f24a8e..1b3b2b4 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -14,6 +14,32 @@ inline constexpr const char* SDK_AGENT = "absmartly-cpp-sdk"; namespace absmartly { +namespace { + +// The collector reads X-Application-Version as a 64-bit integer and rejects anything else, so +// only a whole number of 1 to 18 digits is sent as-is; anything else is sent as "0", as in +// java-sdk Client.applicationVersionHeader and javascript-sdk applicationVersionHeader. +std::string application_version_header(const std::string& version) { + const char* whitespace = " \t\n\r\f\v"; + const auto first = version.find_first_not_of(whitespace); + if (first == std::string::npos) { + return "0"; + } + const auto last = version.find_last_not_of(whitespace); + std::string trimmed = version.substr(first, last - first + 1); + if (trimmed.size() > 18) { + return "0"; + } + for (const char c : trimmed) { + if (c < '0' || c > '9') { + return "0"; + } + } + return trimmed; +} + +} // namespace + Client::Client(const ClientConfig& config, std::shared_ptr http_client) : http_client_(std::move(http_client)) { if (!http_client_) { @@ -48,7 +74,7 @@ Client::Client(const ClientConfig& config, std::shared_ptr http_clie headers_["X-API-Key"] = config.api_key; headers_["X-Application"] = config.application; headers_["X-Environment"] = config.environment; - headers_["X-Application-Version"] = "0"; + headers_["X-Application-Version"] = application_version_header(config.application_version); headers_["X-Agent"] = SDK_AGENT; headers_["Content-Type"] = "application/json"; diff --git a/src/context.cpp b/src/context.cpp index ffbc319..65e4c8f 100644 --- a/src/context.cpp +++ b/src/context.cpp @@ -14,6 +14,15 @@ static int64_t now_millis() { return std::chrono::duration_cast(now.time_since_epoch()).count(); } +// Arm 0 always holds the unit out. In a 3-arm holdout, arm 1 holds it out only of +// covered experiments that are not full-on. The arity is the split's length, never +// holdoutType (javascript-sdk isHeldOutBy). +static bool is_held_out_by(int holdout_variant, size_t holdout_arm_count, int full_on_variant) { + if (holdout_variant == 0) return true; + if (holdout_arm_count == 3 && holdout_variant == 1) return full_on_variant == 0; + return false; +} + template static void prepend_all(std::vector& queue, std::vector& items) { queue.insert(queue.begin(), @@ -155,13 +164,20 @@ void Context::set_unit(const std::string& unit_type, const nlohmann::json& uid) } void Context::invalidate_assignments_pinned_with_missing_unit(const std::string& unit_type) { - // A split rule that matched without its unit gave the full-on variant. With the unit - // now set it is re-randomised, but only while unexposed: rebuilding an exposed one - // would queue a second, conflicting exposure. + // A split rule that matched without its unit gave the full-on variant, and a holdout + // could not be resolved without it (a null pin). With the unit now set the assignment + // is resolved again, but only while unexposed: rebuilding an exposed one would queue a + // second, conflicting exposure. for (auto it = assignments_.begin(); it != assignments_.end();) { const auto& assignment = it->second; - if (assignment.rule_override && assignment.rule_missing_unit && !assignment.exposed && - assignment.unit_type == unit_type) { + bool missing_holdout = false; + if (assignment.holdouts) { + for (const auto& pin : *assignment.holdouts) { + missing_holdout = missing_holdout || !pin.assignment; + } + } + if ((missing_holdout || (assignment.rule_override && assignment.rule_missing_unit)) && + !assignment.exposed && assignment.unit_type == unit_type) { it = assignments_.erase(it); } else { ++it; @@ -278,11 +294,11 @@ int Context::treatment(const std::string& experiment_name) { auto& assignment = get_or_create_assignment(experiment_name); // Read before the exposure logger runs: it may refresh or override, replacing this entry. - int variant = assignment.variant; + const int variant = assignment.variant; if (!assignment.exposed) { assignment.exposed = true; - queue_exposure(experiment_name, assignment); + trigger_exposures(experiment_name, assignment); } return variant; @@ -299,30 +315,45 @@ int Context::peek(const std::string& experiment_name) { // first one the unit is in (assigned, overridden or rule-assigned) wins, and only it is exposed: // a candidate that was checked but lost was never seen by the user. If the winner's variant does // not define the key the caller default applies; later candidates are not tried, or the arm the -// unit got would decide which experiment it is counted in. Matches the Java SDK's -// Context.getVariableAssignment. -std::pair Context::variable_assignment(const std::string& key) { +// unit got would decide which experiment it is counted in. With no winner, the first held-out +// candidate supplies its control value. Each candidate visited queues its holdouts' exposures +// into holdout_events (null for peek). Matches the Java SDK's Context.getVariableAssignment. +std::pair Context::variable_assignment(const std::string& key, + std::vector* holdout_events) { auto var_it = index_variables_.find(key); if (var_it == index_variables_.end()) { return {nullptr, nullptr}; } + std::pair suppressed_fallback{nullptr, nullptr}; for (const auto* experiment_index : var_it->second) { const std::string& experiment_name = experiment_index->data->name; - auto& assignment = get_or_create_assignment(experiment_name); + auto& assignment = get_or_create_assignment(experiment_name, experiment_index); + if (holdout_events != nullptr && assignment.holdouts) { + enqueue_holdout_exposures(*assignment.holdouts, *holdout_events); + } if (assignment.assigned || assignment.overridden || assignment.rule_override) { return {&experiment_name, &assignment}; } + if (assignment.suppressed && suppressed_fallback.second == nullptr) { + suppressed_fallback = {&experiment_name, &assignment}; + } } - return {nullptr, nullptr}; + return suppressed_fallback; } nlohmann::json Context::variable_value(const std::string& key, const nlohmann::json& default_value) { check_ready(true); - auto [experiment_name, assignment] = variable_assignment(key); + // No event logger runs until every exposure of this read is queued, so a logger that + // refreshes or finalizes cannot change the walk or leave part of the read unpublished. + std::vector events; + auto [experiment_name, assignment] = variable_assignment(key, &events); if (assignment == nullptr) { + for (const auto& event : events) { + emit_event("exposure", event); + } return default_value; } @@ -331,16 +362,27 @@ nlohmann::json Context::variable_value(const std::string& key, const nlohmann::j if (!assignment->exposed) { assignment->exposed = true; - queue_exposure(*experiment_name, *assignment); + // A held-out winner publishes no exposure of its own; its holdouts were queued above. + if (!assignment->suppressed || assignment->overridden || assignment->rule_override) { + if (events.empty()) { + // No holdout exposures: no batch, as in 1.0.1. + queue_exposure(*experiment_name, *assignment); + return value; + } + events.push_back(enqueue_exposure(*experiment_name, *assignment)); + } } + for (const auto& event : events) { + emit_event("exposure", event); + } return value; } nlohmann::json Context::peek_variable_value(const std::string& key, const nlohmann::json& default_value) { check_ready(true); - const auto* assignment = variable_assignment(key).second; + const auto* assignment = variable_assignment(key, nullptr).second; if (assignment == nullptr) { return default_value; } @@ -604,8 +646,19 @@ void Context::refresh(const ContextData& new_data) { } } - data_ = new_data; - build_index(); + // The payload is copied and indexed before anything is installed, so a failure (bad_alloc) + // leaves the installed data and its index untouched. new_data may be data() itself. + ContextData installed = new_data; + std::map index; + std::map> index_variables; + std::vector errors; + index_data(installed, index, index_variables, errors); + // Moving keeps the element addresses the new index points to. + data_ = std::move(installed); + index_ = std::move(index); + index_variables_ = std::move(index_variables); + ++data_seq_; + for (const auto& name : unloaded_overrides) { auto exp_it = index_.find(name); if (exp_it == index_.end()) { @@ -623,6 +676,10 @@ void Context::refresh(const ContextData& new_data) { hashes_.clear(); assigners_.clear(); + for (const auto& error : errors) { + emit_event("error", error); + } + nlohmann::json refresh_data; nlohmann::json refresh_exps = nlohmann::json::array(); for (const auto& exp : data_.experiments) { @@ -632,17 +689,22 @@ void Context::refresh(const ContextData& new_data) { emit_event("refresh", refresh_data); } -Assignment& Context::get_or_create_assignment(const std::string& experiment_name) { +Assignment& Context::get_or_create_assignment(const std::string& experiment_name, const ExperimentIndex* experiment) { bool has_custom = cassignments_.count(experiment_name) > 0; bool has_override = overrides_.count(experiment_name) > 0; - auto exp_it = index_.find(experiment_name); - const ExperimentIndex* experiment = (exp_it != index_.end()) ? &exp_it->second : nullptr; + if (experiment == nullptr) { + auto exp_it = index_.find(experiment_name); + experiment = (exp_it != index_.end()) ? &exp_it->second : nullptr; + } else { + ++index_reuses_; + } auto ass_it = assignments_.find(experiment_name); if (ass_it != assignments_.end()) { auto& existing = ass_it->second; if (has_override) { - if (existing.overridden && existing.variant == overrides_[experiment_name]) { + if (existing.overridden && existing.variant == overrides_[experiment_name] && + (experiment == nullptr || holdouts_match(*experiment, existing))) { return existing; } } else if (experiment == nullptr) { @@ -650,11 +712,15 @@ Assignment& Context::get_or_create_assignment(const std::string& experiment_name if (!existing.assigned && !existing.rule_override) { return existing; } - } else if (existing.rule_override || !has_custom || cassignments_[experiment_name] == existing.variant) { - // A matching rule wins over a custom assignment, so a custom mismatch is not - // staleness for a rule-won assignment; treating it as stale rebuilt the - // assignment (and re-queued its exposure) on every call. + } else if (existing.suppressed || existing.rule_override || !has_custom || + cassignments_[experiment_name] == existing.variant) { + // A suppressed assignment is forced to variant 0 and a matching rule wins over a + // custom assignment, so a custom mismatch is not staleness for either; treating it + // as stale rebuilt the assignment (and re-queued its exposure) on every call. + // Coverage changes only with the data: an assignment already validated against this + // data load (rule_data_seq) skips the holdout comparison. if (experiment_matches(*experiment->data, existing) && + (existing.rule_data_seq == data_seq_ || holdouts_match(*experiment, existing)) && rule_matches(*experiment, existing) && audience_matches(*experiment->data, existing)) { // Both checks ran against the current attributes; advance the sequence @@ -667,6 +733,30 @@ Assignment& Context::get_or_create_assignment(const std::string& experiment_name Assignment assignment; + // Resolved for overrides too: an override wins, but the holdouts still fire. + if (experiment != nullptr && !experiment->holdouts.empty()) { + const std::string& unit_type = experiment->data->unitType; + auto pins = std::make_shared>(); + pins->reserve(experiment->holdouts.size()); + for (const auto* holdout : experiment->holdouts) { + HoldoutPin pin; + pin.id = holdout->id; + pin.iteration = holdout->iteration; + pin.name = holdout->name; + // The covered experiment's unit type, never the holdout's own. + if (!unit_type.empty()) { + pin.assignment = get_holdout_assignment(*holdout, unit_type); + } + if (pin.assignment && + is_held_out_by(pin.assignment->variant, pin.assignment->arm_count, + experiment->data->fullOnVariant)) { + assignment.suppressed = true; + } + pins->push_back(std::move(pin)); + } + assignment.holdouts = std::move(pins); + } + if (has_override) { if (experiment != nullptr) { assignment.id = experiment->data->id; @@ -689,6 +779,10 @@ Assignment& Context::get_or_create_assignment(const std::string& experiment_name assignment.rule_override = true; assignment.rule_missing_unit = rule->missing_unit; assignment.variant = rule->variant; + } else if (assignment.suppressed) { + // Held out: control, unassigned. Audience, full-on, traffic and custom + // assignment are not consulted, so a holdout beats all of them. + assignment.variant = 0; } else { if (!exp_data.audience.is_null()) { std::string audience_str; @@ -770,7 +864,111 @@ Assignment& Context::get_or_create_assignment(const std::string& experiment_name return assignments_[experiment_name]; } +void Context::trigger_exposures(const std::string& experiment_name, const Assignment& assignment) { + const bool own = !assignment.suppressed || assignment.overridden || assignment.rule_override; + if (!assignment.holdouts) { + if (own) { + queue_exposure(experiment_name, assignment); + } + return; + } + + // Every exposure of this call is queued before any event logger runs, so a logger that + // finalizes (or refreshes) from the first callback still flushes the whole batch. JS + // queues each exposure just before its callback, so there an exposure a logger queues + // from that callback lands between the experiment's and its holdouts'; here it follows + // them. The set published is the same. + // Held by value: a re-entrant event logger may replace this assignment. + const auto holdouts = assignment.holdouts; + std::vector events; + events.reserve(holdouts->size() + 1); + + // A suppressed experiment publishes no exposure of its own; the holdouts record it. + if (own) { + events.push_back(enqueue_exposure(experiment_name, assignment)); + } + + enqueue_holdout_exposures(*holdouts, events); + + for (const auto& event : events) { + emit_event("exposure", event); + } +} + +// The pins from the decision, not a live re-resolution, so a refresh between the decision and +// here cannot publish a holdout exposure from another iteration. +void Context::enqueue_holdout_exposures(const std::vector& holdouts, std::vector& events) { + for (const auto& pin : holdouts) { + if (pin.assignment && !pin.assignment->exposed) { + pin.assignment->exposed = true; + Assignment exposed; + exposed.id = pin.assignment->id; + exposed.unit_type = pin.assignment->unit_type; + exposed.variant = pin.assignment->variant; + exposed.assigned = true; + exposed.eligible = true; + events.push_back(enqueue_exposure(pin.name, exposed)); + } + } +} + +std::shared_ptr Context::get_holdout_assignment(const HoldoutData& holdout, + const std::string& unit_type) { + // Valid while the iteration is unchanged: a same-iteration seed or split edit neither + // re-randomises nor re-exposes the unit. + auto key = std::make_pair(holdout.id, unit_type); + auto it = holdout_assignments_.find(key); + if (it != holdout_assignments_.end() && it->second->iteration == holdout.iteration) { + return it->second; + } + + // Never cached when the unit is missing: it can still be set later. + if (units_.count(unit_type) == 0) { + return nullptr; + } + const std::string hashed = unit_hash(unit_type); + if (hashed.empty()) { + return nullptr; + } + + auto assigner_it = assigners_.find(unit_type); + if (assigner_it == assigners_.end()) { + assigner_it = assigners_.emplace(unit_type, VariantAssigner(hashed)).first; + } + + auto assignment = std::make_shared(); + assignment->id = holdout.id; + assignment->iteration = holdout.iteration; + assignment->unit_type = unit_type; + assignment->variant = assigner_it->second.assign_holdout(holdout.split, holdout.seedHi, holdout.seedLo); + assignment->arm_count = holdout.split.size(); + holdout_assignments_[std::move(key)] = assignment; + return assignment; +} + +bool Context::holdouts_match(const ExperimentIndex& experiment, const Assignment& assignment) { + // (id, iteration) only: a seed, split or name edit must not force a second exposure. + if (!assignment.holdouts) { + return experiment.holdouts.empty(); + } + const size_t pinned = assignment.holdouts->size(); + if (experiment.holdouts.size() != pinned) { + return false; + } + for (size_t i = 0; i < pinned; ++i) { + const auto& pin = (*assignment.holdouts)[i]; + if (experiment.holdouts[i]->id != pin.id || experiment.holdouts[i]->iteration != pin.iteration) { + return false; + } + } + return true; +} + void Context::queue_exposure(const std::string& experiment_name, const Assignment& assignment) { + emit_event("exposure", enqueue_exposure(experiment_name, assignment)); +} + +nlohmann::json Context::enqueue_exposure(const std::string& experiment_name, const Assignment& assignment) { Exposure exposure; exposure.id = assignment.id; exposure.name = experiment_name; @@ -793,18 +991,38 @@ void Context::queue_exposure(const std::string& experiment_name, const Assignmen exposures_.push_back(std::move(exposure)); pending_++; - emit_event("exposure", exposure_data); + return exposure_data; } -void Context::build_index() { - ++data_seq_; - index_.clear(); - index_variables_.clear(); +void Context::index_data(const ContextData& data, std::map& index, + std::map>& index_variables, + std::vector& errors) { + std::map holdouts_by_id; - for (const auto& exp : data_.experiments) { + // A holdout without a split cannot be assigned, so it covers nothing. + for (const auto& holdout : data.holdouts) { + if (!holdout.split.empty()) { + holdouts_by_id[holdout.id] = &holdout; + } + } + + for (const auto& exp : data.experiments) { ExperimentIndex entry; entry.data = &exp; + // Dangling ids are ignored and duplicates collapse, as in javascript-sdk. + for (int holdout_id : exp.holdoutIds) { + auto holdout_it = holdouts_by_id.find(holdout_id); + if (holdout_it == holdouts_by_id.end()) { + continue; + } + auto pos = std::lower_bound(entry.holdouts.begin(), entry.holdouts.end(), holdout_id, + [](const HoldoutData* existing, int id) { return existing->id < id; }); + if (pos == entry.holdouts.end() || (*pos)->id != holdout_id) { + entry.holdouts.insert(pos, holdout_it->second); + } + } + // A value that is not a JSON object, like an object without a "rules" array, // means no rules for this experiment. No error event: JS and Java only log it, // and the context is healthy, so a logger must not see it as a failure. @@ -830,8 +1048,8 @@ void Context::build_index() { } } } catch (const nlohmann::json::exception& e) { - emit_event("error", {{"message", "Failed to parse variant config for " + exp.name}, - {"error", e.what()}, {"variant", i}}); + errors.push_back({{"message", "Failed to parse variant config for " + exp.name}, + {"error", e.what()}, {"variant", i}}); } } } else if (variant.config.is_object()) { @@ -843,13 +1061,13 @@ void Context::build_index() { entry.variables.push_back(std::move(parsed)); } - index_[exp.name] = std::move(entry); + index[exp.name] = std::move(entry); } - for (auto& [exp_name, entry] : index_) { + for (auto& [exp_name, entry] : index) { for (const auto& var_map : entry.variables) { for (const auto& [key, _] : var_map) { - auto& vec = index_variables_[key]; + auto& vec = index_variables[key]; auto pos = std::lower_bound(vec.begin(), vec.end(), entry.data->id, [](const ExperimentIndex* existing, int id) { return existing->data->id < id; }); if (pos == vec.end() || (*pos)->data->id != entry.data->id) { @@ -858,6 +1076,21 @@ void Context::build_index() { } } } + +} + +void Context::build_index() { + std::map index; + std::map> index_variables; + std::vector errors; + index_data(data_, index, index_variables, errors); + index_ = std::move(index); + index_variables_ = std::move(index_variables); + ++data_seq_; + // Reported once the index is installed, so a logger reading the context sees the new data. + for (const auto& error : errors) { + emit_event("error", error); + } } bool Context::experiment_matches(const ExperimentData& experiment, const Assignment& assignment) const { @@ -951,9 +1184,9 @@ bool Context::rule_matches(const ExperimentIndex& experiment, Assignment& assign } bool Context::audience_matches(const ExperimentData& experiment, Assignment& assignment) { - // A rule-won assignment never consulted the audience, so an audience change cannot - // make it stale. - if (assignment.rule_override) { + // A rule-won or held-out assignment never consulted the audience, so an audience change + // cannot make it stale. + if (assignment.rule_override || assignment.suppressed) { return true; } diff --git a/src/variant_assigner.cpp b/src/variant_assigner.cpp index 8d9f71b..631acce 100644 --- a/src/variant_assigner.cpp +++ b/src/variant_assigner.cpp @@ -14,15 +14,21 @@ static inline void put_le32(uint8_t* buf, uint32_t val) { buf[3] = static_cast((val >> 24) & 0xFF); } -int VariantAssigner::assign(const std::vector& split, int32_t seed_hi, int32_t seed_lo) const { +uint32_t VariantAssigner::hash(int32_t seed_hi, int32_t seed_lo) const { uint8_t buffer[12]; put_le32(buffer, static_cast(seed_lo)); put_le32(buffer + 4, static_cast(seed_hi)); put_le32(buffer + 8, unit_hash_); + return murmur3_32(buffer, 12, 0); +} - uint32_t hash = murmur3_32(buffer, 12, 0); - double probability = static_cast(hash) / 0x100000000ULL; +int VariantAssigner::assign(const std::vector& split, int32_t seed_hi, int32_t seed_lo) const { + double probability = static_cast(hash(seed_hi, seed_lo)) / 0x100000000ULL; return choose_variant(split, probability); } +int VariantAssigner::assign_holdout(const std::vector& split, int32_t seed_hi, int32_t seed_lo) const { + return choose_variant(split, hash(seed_hi, seed_lo) * (1.0 / 0xffffffffU)); +} + } // namespace absmartly diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 1b2a81f..92a02df 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -16,8 +16,10 @@ add_executable(absmartly_tests context_test.cpp system_attributes_test.cpp assignment_rules_test.cpp + holdouts_test.cpp http_integration_test.cpp shared_variable_key_test.cpp + client_test.cpp ) target_link_libraries(absmartly_tests PRIVATE absmartly-sdk Catch2::Catch2WithMain) @@ -27,3 +29,11 @@ target_compile_definitions(absmartly_tests PRIVATE ABSMARTLY_PROJECT_VERSION="${ include(CTest) include(Catch) catch_discover_tests(absmartly_tests) +target_compile_definitions(absmartly_tests PRIVATE ABSMARTLY_TEST_FIXTURES_DIR="${CMAKE_CURRENT_SOURCE_DIR}/fixtures") + +# Public headers stay clean under strict consumer warnings. +add_library(absmartly_public_headers_check OBJECT public_headers_check.cpp) +target_link_libraries(absmartly_public_headers_check PRIVATE absmartly-sdk) +if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + target_compile_options(absmartly_public_headers_check PRIVATE -Wfloat-equal -Werror) +endif() diff --git a/tests/assignment_rules_test.cpp b/tests/assignment_rules_test.cpp index 102a334..1af5c9c 100644 --- a/tests/assignment_rules_test.cpp +++ b/tests/assignment_rules_test.cpp @@ -1,3 +1,4 @@ +#include "context_test_access.h" #include #include #include @@ -516,14 +517,7 @@ TEST_CASE("Assignment rules: caching", "[assignment-rules]") { } } -namespace absmartly { -struct ContextTestAccess { - static Assignment& assignment(Context& ctx, const char* name) { return ctx.assignments_.at(name); } - static int data_seq(const Context& ctx) { return ctx.data_seq_; } - static const json& attributes_map(const Context& ctx) { return ctx.get_attributes_map(); } - static json& attributes_map_cache(Context& ctx) { return ctx.attrs_map_cache_; } -}; -} // namespace absmartly + // Losing these caches changes only CPU cost, so the tests poke a stale value into the // cached state and check whether a read recomputes it. diff --git a/tests/client_test.cpp b/tests/client_test.cpp new file mode 100644 index 0000000..00c1392 --- /dev/null +++ b/tests/client_test.cpp @@ -0,0 +1,117 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using namespace absmartly; + +namespace { + +// Records the headers of every request and answers with an empty context. +class CapturingHTTPClient : public HTTPClient { +public: + std::future get(const std::string&, const std::map&, + const std::map& headers) override { + sent.push_back(headers); + return ok(); + } + std::future put(const std::string&, const std::map&, + const std::map& headers, const std::vector&) override { + sent.push_back(headers); + return ok(); + } + std::future post(const std::string&, const std::map&, + const std::map& headers, const std::vector&) override { + sent.push_back(headers); + return ok(); + } + std::vector> sent; + +private: + static std::future ok() { + std::promise promise; + Response response; + response.status_code = 200; + const std::string body = R"({"experiments":[]})"; + response.content.assign(body.begin(), body.end()); + promise.set_value(response); + return promise.get_future(); + } +}; + +std::string sent_version(const std::string& configured) { + ClientConfig config; + config.endpoint = "https://sandbox.absmartly.io/v1"; + config.api_key = "key"; + config.application = "website"; + config.environment = "production"; + config.application_version = configured; + auto http = std::make_shared(); + Client client(config, http); + client.get_context_data().get(); + client.publish(PublishEvent{}).get(); + REQUIRE(http->sent.size() == 2); + REQUIRE(http->sent[0].at("X-Application-Version") == http->sent[1].at("X-Application-Version")); + return http->sent[0].at("X-Application-Version"); +} + +} // namespace + +TEST_CASE("Client: X-Application-Version carries a configured whole-number version", "[client][application-version]") { + REQUIRE(sent_version("") == "0"); + REQUIRE(sent_version("0") == "0"); + REQUIRE(sent_version("7") == "7"); + REQUIRE(sent_version("100204") == "100204"); + REQUIRE(sent_version(" 42\t") == "42"); + REQUIRE(sent_version("000123") == "000123"); + REQUIRE(sent_version("123456789012345678") == "123456789012345678"); + REQUIRE(sent_version(" 123456789012345678 ") == "123456789012345678"); + REQUIRE(sent_version("\v42\f") == "42"); +} + +TEST_CASE("Client: X-Application-Version falls back to 0 for a version the collector cannot read", + "[client][application-version]") { + // As in java-sdk and javascript-sdk: the collector parses the header as a 64-bit integer. + REQUIRE(sent_version("1234567890123456789") == "0"); + REQUIRE(sent_version("2.4.1") == "0"); + REQUIRE(sent_version("-1") == "0"); + REQUIRE(sent_version("+1") == "0"); + REQUIRE(sent_version("1e3") == "0"); + REQUIRE(sent_version("1 2") == "0"); + REQUIRE(sent_version("v12") == "0"); + REQUIRE(sent_version("1/2") == "0"); + REQUIRE(sent_version("10:30") == "0"); + REQUIRE(sent_version(" ") == "0"); + REQUIRE(sent_version("\xd9\xa1") == "0"); // ARABIC-INDIC DIGIT ONE +} + +TEST_CASE("Client: ClientConfig keeps its 1.0.0 structured-binding and initializer shape", "[client][compat]") { + static_assert(std::tuple_size_v == 4); + static_assert(std::is_same_v, std::string>); + ClientConfig config{"https://e/v1", "key", "app", "env"}; + auto& [endpoint, api_key, application, environment] = config; + const auto& [c_endpoint, c_api_key, c_application, c_environment] = std::as_const(config); + REQUIRE(&endpoint == &config.endpoint); + REQUIRE(&api_key == &config.api_key); + REQUIRE(&application == &config.application); + REQUIRE(&environment == &config.environment); + REQUIRE(&c_environment == &config.environment); + REQUIRE(environment == "env"); + REQUIRE(config.application_version.empty()); + auto&& [rvalue_endpoint, r1, r2, rvalue_environment] = std::move(config); + REQUIRE(&rvalue_endpoint == &config.endpoint); + REQUIRE(&rvalue_environment == &config.environment); + const ClientConfig const_config{"https://c/v1", "ck", "capp", "cenv"}; + auto&& [const_rvalue_endpoint, cr1, cr2, const_rvalue_environment] = std::move(const_config); + REQUIRE(&const_rvalue_endpoint == &const_config.endpoint); + REQUIRE(&const_rvalue_environment == &const_config.environment); + auto [moved_endpoint, m1, m2, m3] = std::move(config); + REQUIRE(moved_endpoint == "https://e/v1"); +} diff --git a/tests/context_test_access.h b/tests/context_test_access.h new file mode 100644 index 0000000..c668af4 --- /dev/null +++ b/tests/context_test_access.h @@ -0,0 +1,15 @@ +#pragma once + +#include + +namespace absmartly { + +struct ContextTestAccess { + static Assignment& assignment(Context& ctx, const char* name) { return ctx.assignments_.at(name); } + static int data_seq(const Context& ctx) { return ctx.data_seq_; } + static const nlohmann::json& attributes_map(const Context& ctx) { return ctx.get_attributes_map(); } + static nlohmann::json& attributes_map_cache(Context& ctx) { return ctx.attrs_map_cache_; } + static unsigned long long index_reuses(const Context& ctx) { return ctx.index_reuses_; } +}; + +} // namespace absmartly diff --git a/tests/fixtures/holdouts_context.json b/tests/fixtures/holdouts_context.json new file mode 100644 index 0000000..92f1dbf --- /dev/null +++ b/tests/fixtures/holdouts_context.json @@ -0,0 +1,86 @@ +{ + "experiments":[ + { + "id":1, + "name":"exp_test_holdout", + "iteration":1, + "unitType":"session_id", + "seedHi":3603515, + "seedLo":233373850, + "split":[ + 0.5, + 0.5 + ], + "trafficSeedHi":449867249, + "trafficSeedLo":455443629, + "trafficSplit":[ + 0.0, + 1.0 + ], + "fullOnVariant":0, + "applications":[ + { + "name":"website" + } + ], + "variants":[ + { + "name":"A", + "config":null + }, + { + "name":"B", + "config":"{\"banner.border\":1,\"banner.size\":\"large\"}" + } + ], + "audience": null, + "holdoutIds":[11] + } + ], + "holdouts":[ + { + "id":11, + "name":"holdout_a", + "iteration":1, + "unitType":"session_id", + "seedHi":13, + "seedLo":111, + "split":[ + 0.1, + 0.9 + ], + "trafficSeedHi":0, + "trafficSeedLo":0, + "trafficSplit":[ + 0.0, + 1.0 + ], + "fullOnVariant":0, + "variants":[ + { + "name":"A", + "config":null + }, + { + "name":"B", + "config":null + } + ], + "audience": null, + "holdoutType":"full" + }, + { + "id":12, + "name":"holdout_b", + "iteration":1, + "unitType":"session_id", + "seedHi":1, + "seedLo":222, + "split":[ + 0.05, + 0.05, + 0.9 + ] + } + ] +} diff --git a/tests/fixtures/holdouts_forward_compat_context.json b/tests/fixtures/holdouts_forward_compat_context.json new file mode 100644 index 0000000..27e1a28 --- /dev/null +++ b/tests/fixtures/holdouts_forward_compat_context.json @@ -0,0 +1,77 @@ +{ + "experiments": [ + { + "id": 1, + "name": "exp_covered", + "iteration": 1, + "unitType": "session_id", + "seedHi": 100, + "seedLo": 200, + "split": [0.5, 0.5], + "trafficSeedHi": 1, + "trafficSeedLo": 2, + "trafficSplit": [0.0, 1.0], + "fullOnVariant": 0, + "variants": [{"name": "A", "config": null}, {"name": "B", "config": null}], + "audience": null, + "holdoutIds": [12, 11], + "holdoutType": "future_type", + "futureExperimentScalar": 1, + "futureExperimentObject": {"nested": [1, 2]}, + "futureExperimentArray": [{"a": 1}] + }, + { + "id": 2, + "name": "exp_uncovered", + "iteration": 1, + "unitType": "session_id", + "seedHi": 100, + "seedLo": 200, + "split": [0.5, 0.5], + "trafficSeedHi": 1, + "trafficSeedLo": 2, + "trafficSplit": [0.0, 1.0], + "fullOnVariant": 0, + "variants": [{"name": "A", "config": null}, {"name": "B", "config": null}], + "audience": null, + "futureHoldoutLink": {"ids": [11]} + } + ], + "holdouts": [ + { + "id": 11, + "name": "holdout_future", + "iteration": 1, + "unitType": "session_id", + "seedHi": 13, + "seedLo": 111, + "split": [0.1, 0.9], + "trafficSeedHi": 0, + "trafficSeedLo": 0, + "trafficSplit": [0.0, 1.0], + "fullOnVariant": 0, + "variants": [{"name": "A", "config": null}, {"name": "B", "config": null}], + "audience": null, + "holdoutType": "full", + "futureHoldoutScalar": "x", + "futureHoldoutNumber": 3.5, + "futureHoldoutObject": {"schedule": {"startAt": 0, "periodMs": 60000}}, + "futureHoldoutArray": [1, "two", {"three": 3}, [4]], + "switchbackClusters": {"user_id": "/country"} + }, + { + "id": 12, + "name": "holdout_slim", + "iteration": 1, + "unitType": "session_id", + "seedHi": 1, + "seedLo": 222, + "split": [0.1, 0.9], + "futureNull": null, + "futureBool": true + } + ], + "futureRootScalar": 7, + "futureRootObject": {"holdouts": []}, + "futureRootArray": [null] +} diff --git a/tests/holdouts_test.cpp b/tests/holdouts_test.cpp new file mode 100644 index 0000000..a3108fc --- /dev/null +++ b/tests/holdouts_test.cpp @@ -0,0 +1,2536 @@ +#include "context_test_access.h" +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Counts heap allocations so tests can pin the cost of the holdout paths. +static std::atomic g_allocations{0}; +// When positive, the allocation that brings it to zero throws (one-shot failure injection). +static std::atomic g_fail_after{0}; + +void* operator new(std::size_t size) { + ++g_allocations; + if (g_fail_after.load() > 0 && --g_fail_after == 0) throw std::bad_alloc(); + if (void* p = std::malloc(size ? size : 1)) return p; + throw std::bad_alloc(); +} +void operator delete(void* p) noexcept { std::free(p); } +void operator delete(void* p, std::size_t) noexcept { std::free(p); } + +using namespace absmartly; +using json = nlohmann::json; + +// Ported from java-sdk ContextHoldoutTest (core-api/src/test/java/com/absmartly/sdk/ +// ContextHoldoutTest.java, blob 88f716cd) and checked against javascript-sdk src/context.ts (the +// reference), with the same units, seeds and splits, so every SDK resolves the same holdout arms. +// +// A holdout arrives in ContextData::holdouts; a covered experiment lists its id in holdoutIds. +// Arm 0 holds the unit out; in a 3-arm holdout (split of length 3) arm 1 holds it out of covered +// experiments that are not full-on. A held-out unit gets control and no exposure of its own; the +// holdout publishes one ordinary exposure per (holdout, unit type) and iteration. + +namespace { + +const char* UNIT_TYPE = "session_id"; +const char* UID = "e791e240fcd3df7d238cfc285f475e8152fcc0ec"; +const char* UID_NOT_HELD_OUT = "b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3"; + +// split[0.5,0.5], seedHi=100, seedLo=200 -> variant 1 for UID, variant 0 for UID_NOT_HELD_OUT. +const int NORMAL_SEED_HI = 100; +const int NORMAL_SEED_LO = 200; +const int NORMAL_VARIANT = 1; + +// split[0.1,0.9]: 13/111 holds UID out (arm 0) and not UID_NOT_HELD_OUT (arm 1). +const int HOLDOUT_A_SEED_HI = 13; +const int HOLDOUT_A_SEED_LO = 111; +// split[0.1,0.9]: 1/222 holds neither out (arm 1). +const int HOLDOUT_B_SEED_HI = 1; +const int HOLDOUT_B_SEED_LO = 222; + +// For UID on split[0.3,0.3,0.4]: seedLo=1 -> arm 0, seedLo=3 -> arm 1, seedLo=0 -> arm 2. +const std::vector THREE_ARM_SPLIT = {0.3, 0.3, 0.4}; +const int THREE_ARM_0_SEED_LO = 1; +const int THREE_ARM_1_SEED_LO = 3; +const int THREE_ARM_2_SEED_LO = 0; + +ExperimentData new_experiment(int id, const std::string& name, const std::string& unit_type = UNIT_TYPE, + int full_on_variant = 0) { + ExperimentData experiment; + experiment.id = id; + experiment.name = name; + experiment.unitType = unit_type; + experiment.iteration = 1; + experiment.seedHi = NORMAL_SEED_HI; + experiment.seedLo = NORMAL_SEED_LO; + experiment.split = {0.5, 0.5}; + experiment.trafficSeedHi = 1; + experiment.trafficSeedLo = 2; + experiment.trafficSplit = {0.0, 1.0}; + experiment.fullOnVariant = full_on_variant; + experiment.variants = {{"A", nullptr}, {"B", nullptr}}; + experiment.application = "website"; + return experiment; +} + +ExperimentData new_experiment(int id, const std::string& name, int full_on_variant) { + return new_experiment(id, name, UNIT_TYPE, full_on_variant); +} + +HoldoutData new_holdout(int id, const std::string& name, int seed_hi, int seed_lo, + const std::string& unit_type = UNIT_TYPE, const std::string& holdout_type = "full") { + HoldoutData holdout; + holdout.id = id; + holdout.name = name; + holdout.unitType = unit_type; + holdout.iteration = 1; + holdout.seedHi = seed_hi; + holdout.seedLo = seed_lo; + holdout.split = {0.1, 0.9}; + holdout.holdoutType = holdout_type; + return holdout; +} + +// holdoutType is set for wire fidelity only; the arity comes from split. +HoldoutData new_three_arm_holdout(int id, const std::string& name, int seed_lo) { + HoldoutData holdout = new_holdout(id, name, 0, seed_lo, UNIT_TYPE, "all_full_on"); + holdout.split = THREE_ARM_SPLIT; + return holdout; +} + +ExperimentData covered_by(ExperimentData experiment, std::vector holdout_ids) { + experiment.holdoutIds = std::move(holdout_ids); + return experiment; +} + +ExperimentData with_variables(ExperimentData experiment, const std::string& key) { + experiment.variants = {{"A", json({{key, "control"}}).dump()}, {"B", json({{key, "treatment"}}).dump()}}; + return experiment; +} + +ContextData data_of(std::vector holdouts, std::vector experiments) { + ContextData data; + data.experiments = std::move(experiments); + data.holdouts = std::move(holdouts); + return data; +} + +ContextConfig config_with(const std::string& uid, const std::string& unit_type = UNIT_TYPE) { + ContextConfig config; + config.units[unit_type] = uid; + return config; +} + +// The exposure fields that reach the wire, apart from exposedAt. +struct Expected { + int id; + std::string name; + std::string unit; + int variant; + bool assigned = true; + bool eligible = true; + bool overridden = false; + bool full_on = false; + bool custom = false; + bool audience_mismatch = false; + bool rule_override = false; +}; + +Expected holdout_exposure(int id, const std::string& name, int variant, const std::string& unit = UNIT_TYPE) { + return {id, name, unit, variant}; +} + +Expected own_exposure(int id, const std::string& name, int variant, const std::string& unit = UNIT_TYPE) { + return {id, name, unit, variant}; +} + +json to_json_expected(const Expected& e) { + return {{"id", e.id}, {"name", e.name}, {"unit", e.unit}, {"variant", e.variant}, + {"assigned", e.assigned}, {"eligible", e.eligible}, {"overridden", e.overridden}, + {"fullOn", e.full_on}, {"custom", e.custom}, {"audienceMismatch", e.audience_mismatch}, + {"ruleOverride", e.rule_override}}; +} + +json to_json_actual(const Exposure& e) { + return {{"id", e.id}, {"name", e.name}, {"unit", e.unit}, {"variant", e.variant}, + {"assigned", e.assigned}, {"eligible", e.eligible}, {"overridden", e.overridden}, + {"fullOn", e.fullOn}, {"custom", e.custom}, {"audienceMismatch", e.audienceMismatch}, + {"ruleOverride", e.ruleOverride}}; +} + +// Publishes and compares every exposure, in order, plus the hashed units. +void require_published(Context& context, const std::vector& expected, + const std::vector>& units = {{UNIT_TYPE, UID}}) { + const PublishEvent event = context.publish(); + json actual = json::array(); + for (const auto& exposure : event.exposures) { + actual.push_back(to_json_actual(exposure)); + } + json wanted = json::array(); + for (const auto& exposure : expected) { + wanted.push_back(to_json_expected(exposure)); + } + INFO("published " << actual.dump()); + REQUIRE(actual == wanted); + REQUIRE(event.hashed); + REQUIRE(event.units.size() == units.size()); + for (size_t i = 0; i < units.size(); ++i) { + REQUIRE(event.units[i].type == units[i].first); + REQUIRE(event.units[i].uid == hash_unit(units[i].second)); + } +} + +struct ExposureLog : ContextEventLogger { + std::vector exposures; + std::function on_exposure; + void handle_event(Context& context, const std::string& type, const json& data) override { + if (type != "exposure") return; + exposures.push_back(data); + if (on_exposure) on_exposure(context, data); + } +}; + +struct ThrowingLogger : ContextEventLogger { + std::function throws_on; + void handle_event(Context&, const std::string& type, const json& data) override { + if (type == "exposure" && throws_on(data)) throw std::runtime_error("boom"); + } +}; + +const char* US_RULE = R"({"rules":[{"name":"US Internal Users","type":"assign",)" + R"("conditions":{"and":[{"eq":[{"var":"country"},{"value":"US"}]}]},)" + R"("environments":[],"variant":1}]})"; + +const char* AGE_AUDIENCE = R"({"filter":[{"gte":[{"var":"age"},{"value":20}]}]})"; + +} // namespace + +// --- Two-arm holdouts --------------------------------------------------------------------------- + +TEST_CASE("Holdouts: a held-out unit gets control and only the holdout exposure", "[holdouts]") { + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_holdout_in"), {11})})); + + REQUIRE(context.peek("exp_holdout_in") == 0); + context.treatment("exp_holdout_in"); + require_published(context, {holdout_exposure(11, "holdout_a", 0)}); +} + +TEST_CASE("Holdouts: a not-held-out unit publishes its own exposure and the holdout's arm 1", "[holdouts]") { + Context context(config_with(UID_NOT_HELD_OUT), + data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_holdout_out"), {11})})); + + REQUIRE(context.treatment("exp_holdout_out") == 0); + require_published(context, {own_exposure(1, "exp_holdout_out", 0), holdout_exposure(11, "holdout_a", 1)}, + {{UNIT_TYPE, UID_NOT_HELD_OUT}}); +} + +TEST_CASE("Holdouts: an experiment without holdoutIds is not covered", "[holdouts]") { + Context context(config_with(UID), + data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_holdout_in"), {11}), new_experiment(2, "exp_not_covered")})); + + REQUIRE(context.treatment("exp_holdout_in") == 0); + REQUIRE(context.treatment("exp_not_covered") == NORMAL_VARIANT); + require_published(context, {holdout_exposure(11, "holdout_a", 0), + own_exposure(2, "exp_not_covered", NORMAL_VARIANT)}); +} + +TEST_CASE("Holdouts: the union of two holdouts suppresses, and both publish", "[holdouts][union]") { + Context context(config_with(UID), + data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO), + new_holdout(12, "holdout_b", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {covered_by(new_experiment(1, "exp_multi_holdout"), {11, 12})})); + + REQUIRE(context.treatment("exp_multi_holdout") == 0); + require_published(context, {holdout_exposure(11, "holdout_a", 0), holdout_exposure(12, "holdout_b", 1)}); +} + +TEST_CASE("Holdouts: the union applies when only the higher-id holdout holds the unit out", "[holdouts][union]") { + // Fails an implementation that stops at, or only consults, the first holdout. + Context context(config_with(UID), + data_of({new_holdout(11, "holdout_low_id", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO), + new_holdout(12, "holdout_high_id", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_union_high_id_decides"), {11, 12})})); + + REQUIRE(context.treatment("exp_union_high_id_decides") == 0); + require_published(context, {holdout_exposure(11, "holdout_low_id", 1), holdout_exposure(12, "holdout_high_id", 0)}); +} + +TEST_CASE("Holdouts: a unit held out by neither holdout is not suppressed", "[holdouts][union]") { + Context context(config_with(UID_NOT_HELD_OUT), + data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO), + new_holdout(12, "holdout_b", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {covered_by(new_experiment(1, "exp_multi_holdout_miss"), {11, 12})})); + + REQUIRE(context.treatment("exp_multi_holdout_miss") == 0); + require_published(context, {own_exposure(1, "exp_multi_holdout_miss", 0), holdout_exposure(11, "holdout_a", 1), + holdout_exposure(12, "holdout_b", 1)}, + {{UNIT_TYPE, UID_NOT_HELD_OUT}}); +} + +TEST_CASE("Holdouts: a holdout suppresses a full-on experiment", "[holdouts]") { + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_fullon_holdout", 2), {11})})); + + REQUIRE(context.treatment("exp_fullon_holdout") == 0); +} + +// --- Three-arm holdouts ------------------------------------------------------------------------- + +TEST_CASE("Holdout arms: arm 0 holds out full-on and non-full-on experiments", "[holdouts][arms]") { + Context context(config_with(UID), + data_of({new_three_arm_holdout(21, "holdout_three_arm", THREE_ARM_0_SEED_LO)}, + {covered_by(new_experiment(1, "exp_three_arm_0_non_fullon"), {21}), + covered_by(new_experiment(2, "exp_three_arm_0_fullon", 2), {21})})); + + REQUIRE(context.treatment("exp_three_arm_0_non_fullon") == 0); + REQUIRE(context.treatment("exp_three_arm_0_fullon") == 0); + require_published(context, {holdout_exposure(21, "holdout_three_arm", 0)}); +} + +TEST_CASE("Holdout arms: arm 1 forces a non-full-on experiment to control and assigns a full-on one", + "[holdouts][arms]") { + Context context(config_with(UID), + data_of({new_three_arm_holdout(21, "holdout_three_arm", THREE_ARM_1_SEED_LO)}, + {covered_by(new_experiment(1, "exp_three_arm_1_non_fullon"), {21}), + covered_by(new_experiment(2, "exp_three_arm_1_fullon", 2), {21})})); + + REQUIRE(context.treatment("exp_three_arm_1_non_fullon") == 0); + REQUIRE(context.treatment("exp_three_arm_1_fullon") == 2); + + Expected full_on = own_exposure(2, "exp_three_arm_1_fullon", 2); + full_on.full_on = true; + require_published(context, {holdout_exposure(21, "holdout_three_arm", 1), full_on}); +} + +TEST_CASE("Holdout arms: arm 2 assigns both experiment kinds normally", "[holdouts][arms]") { + Context context(config_with(UID), + data_of({new_three_arm_holdout(21, "holdout_three_arm", THREE_ARM_2_SEED_LO)}, + {covered_by(new_experiment(1, "exp_three_arm_2_non_fullon"), {21}), + covered_by(new_experiment(2, "exp_three_arm_2_fullon", 2), {21})})); + + REQUIRE(context.treatment("exp_three_arm_2_non_fullon") == NORMAL_VARIANT); + REQUIRE(context.treatment("exp_three_arm_2_fullon") == 2); + + Expected full_on = own_exposure(2, "exp_three_arm_2_fullon", 2); + full_on.full_on = true; + require_published(context, {own_exposure(1, "exp_three_arm_2_non_fullon", NORMAL_VARIANT), + holdout_exposure(21, "holdout_three_arm", 2), full_on}); +} + +TEST_CASE("Holdout arms: a 2-arm holdout wins the union over a 3-arm arm 2", "[holdouts][arms][union]") { + Context context(config_with(UID), + data_of({new_holdout(11, "holdout_two_arm", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO), + new_three_arm_holdout(22, "holdout_three_arm", THREE_ARM_2_SEED_LO)}, + {covered_by(new_experiment(1, "exp_union_two_arm_wins"), {11, 22})})); + + REQUIRE(context.treatment("exp_union_two_arm_wins") == 0); + require_published(context, {holdout_exposure(11, "holdout_two_arm", 0), holdout_exposure(22, "holdout_three_arm", 2)}); +} + +TEST_CASE("Holdout arms: a 3-arm arm 1 wins the union over a 2-arm arm 1", "[holdouts][arms][union]") { + Context context(config_with(UID), + data_of({new_holdout(11, "holdout_two_arm", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO), + new_three_arm_holdout(22, "holdout_three_arm", THREE_ARM_1_SEED_LO)}, + {covered_by(new_experiment(1, "exp_union_three_arm_wins"), {11, 22})})); + + REQUIRE(context.treatment("exp_union_three_arm_wins") == 0); + require_published(context, {holdout_exposure(11, "holdout_two_arm", 1), holdout_exposure(22, "holdout_three_arm", 1)}); +} + +TEST_CASE("Holdout arms: arm 1 defers a full-on experiment to the normal path, so a strict audience still applies", + "[holdouts][arms]") { + for (int seed_lo : {THREE_ARM_1_SEED_LO, THREE_ARM_2_SEED_LO}) { + const int arm = seed_lo == THREE_ARM_1_SEED_LO ? 1 : 2; + auto experiment = covered_by(new_experiment(1, "exp_three_arm_audience_fullon", 2), {21}); + experiment.audienceStrict = true; + experiment.audience = AGE_AUDIENCE; + Context context(config_with(UID), data_of({new_three_arm_holdout(21, "holdout_three_arm", seed_lo)}, {experiment})); + context.set_attribute("age", 5); + + REQUIRE(context.treatment("exp_three_arm_audience_fullon") == 0); + + Expected own = own_exposure(1, "exp_three_arm_audience_fullon", 0); + own.assigned = false; + own.audience_mismatch = true; + require_published(context, {own, holdout_exposure(21, "holdout_three_arm", arm)}); + } +} + +TEST_CASE("Holdout arms: the arity comes from the split, not holdoutType", "[holdouts][arms]") { + // A 3-arm split labelled "full" (or not labelled at all) is still 3-arm, and a 2-arm split + // labelled "all_full_on" is still 2-arm (scenario 222). + for (const std::string type : {"", "full"}) { + auto holdout = new_three_arm_holdout(21, "holdout_three_arm", THREE_ARM_1_SEED_LO); + holdout.holdoutType = type; + Context context(config_with(UID), data_of({holdout}, {covered_by(new_experiment(1, "exp_non_fullon"), {21})})); + REQUIRE(context.treatment("exp_non_fullon") == 0); + } + + auto two_arm = new_holdout(31, "holdout_two_arm", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO, UNIT_TYPE, "all_full_on"); + Context context(config_with(UID), data_of({two_arm}, {covered_by(new_experiment(1, "exp_non_fullon"), {31})})); + REQUIRE(context.treatment("exp_non_fullon") == NORMAL_VARIANT); +} + +// --- Missing units and malformed coverage ------------------------------------------------------ + +TEST_CASE("Holdouts: an unconfigured unit type gets control and publishes nothing", "[holdouts]") { + Context context(config_with(UID), + data_of({new_holdout(11, "holdout_user", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO, "user_id")}, + {covered_by(new_experiment(1, "exp_user_holdout", "user_id", 0), {11})})); + + REQUIRE(context.peek("exp_user_holdout") == 0); + context.treatment("exp_user_holdout"); + // The experiment's own unassigned exposure (no unit) is unchanged from an uncovered one; + // the holdout cannot be evaluated, so it publishes nothing. + const auto event = context.publish(); + REQUIRE(std::none_of(event.exposures.begin(), event.exposures.end(), + [](const Exposure& e) { return e.id == 11; })); +} + +TEST_CASE("Holdouts: assigns normally without a holdouts key", "[holdouts]") { + Context context(config_with(UID), data_of({}, {new_experiment(1, "exp_no_holdouts_key")})); + REQUIRE(context.peek("exp_no_holdouts_key") == NORMAL_VARIANT); +} + +TEST_CASE("Holdouts: a holdout id missing from holdouts is ignored", "[holdouts]") { + Context context(config_with(UID), data_of({}, {covered_by(new_experiment(1, "exp_dangling_holdout_id"), {999})})); + REQUIRE(context.peek("exp_dangling_holdout_id") == NORMAL_VARIANT); + context.treatment("exp_dangling_holdout_id"); + require_published(context, {own_exposure(1, "exp_dangling_holdout_id", NORMAL_VARIANT)}); +} + +// --- Precedence --------------------------------------------------------------------------------- + +TEST_CASE("Holdouts: a custom assignment cannot override a held-out unit", "[holdouts][precedence]") { + auto config = config_with(UID); + config.custom_assignments["exp_holdout_custom"] = 3; + Context context(config, data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_holdout_custom"), {11})})); + + REQUIRE(context.peek("exp_holdout_custom") == 0); +} + +TEST_CASE("Holdouts: a held-out assignment with a custom assignment is reused from the cache", "[holdouts][cache]") { + auto config = config_with(UID); + config.custom_assignments["exp_holdout_custom_cache"] = 3; + Context context(config, data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_holdout_custom_cache"), {11})})); + + REQUIRE(context.treatment("exp_holdout_custom_cache") == 0); + REQUIRE(context.treatment("exp_holdout_custom_cache") == 0); + REQUIRE(context.pending() == 1); +} + +TEST_CASE("Holdouts: an override takes precedence over a holdout", "[holdouts][precedence]") { + auto config = config_with(UID); + config.overrides["exp_holdout_override"] = 3; + Context context(config, data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_holdout_override"), {11})})); + + REQUIRE(context.peek("exp_holdout_override") == 3); +} + +TEST_CASE("Holdouts: treatment on an overridden experiment still publishes the holdout, for both arms", + "[holdouts][precedence]") { + for (const char* uid : {UID, UID_NOT_HELD_OUT}) { + const int arm = uid == UID ? 0 : 1; + auto config = config_with(uid); + config.overrides["exp_holdout_override"] = 3; + Context context(config, data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_holdout_override"), {11})})); + + REQUIRE(context.treatment("exp_holdout_override") == 3); + + Expected own = own_exposure(1, "exp_holdout_override", 3); + own.assigned = false; + own.overridden = true; + require_published(context, {own, holdout_exposure(11, "holdout_a", arm)}, {{UNIT_TYPE, uid}}); + } +} + +TEST_CASE("Holdouts: a holdout takes precedence over a strict audience mismatch", "[holdouts][precedence]") { + auto experiment = covered_by(new_experiment(1, "exp_holdout_audience"), {11}); + experiment.audienceStrict = true; + experiment.audience = AGE_AUDIENCE; + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {experiment})); + context.set_attribute("age", 5); + + REQUIRE(context.peek("exp_holdout_audience") == 0); + context.treatment("exp_holdout_audience"); + // Suppressed: no exposure of its own, so no audienceMismatch exposure either. + require_published(context, {holdout_exposure(11, "holdout_a", 0)}); +} + +// --- Exposure once per (holdout, unit type) ---------------------------------------------------- + +TEST_CASE("Holdouts: the holdout publishes once, not once per suppressed experiment", "[holdouts][exposure]") { + Context context(config_with(UID), + data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_shared_a"), {11}), + covered_by(new_experiment(2, "exp_shared_b"), {11})})); + + REQUIRE(context.treatment("exp_shared_a") == 0); + REQUIRE(context.treatment("exp_shared_b") == 0); + require_published(context, {holdout_exposure(11, "holdout_a", 0)}); +} + +TEST_CASE("Holdouts: the holdout publishes once when the covered experiments are not suppressed", + "[holdouts][exposure]") { + Context context(config_with(UID_NOT_HELD_OUT), + data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_shared_a"), {11}), + covered_by(new_experiment(2, "exp_shared_b"), {11})})); + + context.treatment("exp_shared_a"); + context.treatment("exp_shared_b"); + require_published(context, {own_exposure(1, "exp_shared_a", 0), holdout_exposure(11, "holdout_a", 1), + own_exposure(2, "exp_shared_b", 0)}, + {{UNIT_TYPE, UID_NOT_HELD_OUT}}); +} + +TEST_CASE("Holdouts: repeated calls reuse the cached suppressed assignment", "[holdouts][cache]") { + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_holdout_cache"), {11})})); + + REQUIRE(context.treatment("exp_holdout_cache") == 0); + REQUIRE(context.treatment("exp_holdout_cache") == 0); + REQUIRE(context.pending() == 1); +} + +// --- Refresh ------------------------------------------------------------------------------------ + +TEST_CASE("Holdouts: a same-iteration seed change keeps the arm and does not re-expose", "[holdouts][refresh]") { + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_holdout_seed_thrash"), {11})})); + + REQUIRE(context.treatment("exp_holdout_seed_thrash") == 0); + REQUIRE(context.pending() == 1); + + context.refresh(data_of({new_holdout(11, "holdout_a", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {covered_by(new_experiment(1, "exp_holdout_seed_thrash"), {11})})); + + REQUIRE(context.treatment("exp_holdout_seed_thrash") == 0); + REQUIRE(context.pending() == 1); +} + +TEST_CASE("Holdouts: a cosmetic holdout edit does not re-expose a held-out unit", "[holdouts][refresh]") { + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_holdout_cosmetic"), {11})})); + + REQUIRE(context.treatment("exp_holdout_cosmetic") == 0); + REQUIRE(context.pending() == 1); + + auto renamed = new_holdout(11, "holdout_a_renamed", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO); + renamed.holdoutType = "all_full_on"; + context.refresh(data_of({renamed}, {covered_by(new_experiment(1, "exp_holdout_cosmetic"), {11})})); + + REQUIRE(context.treatment("exp_holdout_cosmetic") == 0); + REQUIRE(context.pending() == 1); +} + +TEST_CASE("Holdouts: a cosmetic holdout edit does not duplicate the covered experiment's exposure", + "[holdouts][refresh]") { + Context context(config_with(UID_NOT_HELD_OUT), + data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_holdout_cosmetic_covered"), {11})})); + + REQUIRE(context.treatment("exp_holdout_cosmetic_covered") == 0); + REQUIRE(context.pending() == 2); + + context.refresh(data_of({new_holdout(11, "holdout_a_renamed", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_holdout_cosmetic_covered"), {11})})); + + REQUIRE(context.treatment("exp_holdout_cosmetic_covered") == 0); + REQUIRE(context.pending() == 2); +} + +TEST_CASE("Holdouts: an iteration bump re-randomises into exactly one new arm", "[holdouts][refresh]") { + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {covered_by(new_experiment(1, "exp_holdout_iteration"), {11})})); + + REQUIRE(context.treatment("exp_holdout_iteration") == NORMAL_VARIANT); + REQUIRE(context.pending() == 2); + + auto new_epoch = new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO); + new_epoch.iteration = 2; + context.refresh(data_of({new_epoch}, {covered_by(new_experiment(1, "exp_holdout_iteration"), {11})})); + + REQUIRE(context.treatment("exp_holdout_iteration") == 0); + REQUIRE(context.pending() == 3); + REQUIRE(context.treatment("exp_holdout_iteration") == 0); + REQUIRE(context.pending() == 3); +} + +TEST_CASE("Holdouts: a same-iteration seed change does not desync a newly evaluated experiment from the pinned arm", + "[holdouts][refresh]") { + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_holdout_desync_a"), {11})})); + + REQUIRE(context.treatment("exp_holdout_desync_a") == 0); + REQUIRE(context.pending() == 1); + + context.refresh(data_of({new_holdout(11, "holdout_a", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {covered_by(new_experiment(1, "exp_holdout_desync_a"), {11}), + covered_by(new_experiment(2, "exp_holdout_desync_b"), {11})})); + + REQUIRE(context.treatment("exp_holdout_desync_b") == 0); + REQUIRE(context.treatment("exp_holdout_desync_a") == 0); + require_published(context, {holdout_exposure(11, "holdout_a", 0)}); +} + +TEST_CASE("Holdouts: a same-iteration 2 to 3 arm change keeps arm 1's 2-arm meaning", "[holdouts][refresh][arms]") { + Context context(config_with(UID), data_of({new_holdout(31, "holdout_arity", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {covered_by(new_experiment(1, "exp_arity_2to3_a"), {31})})); + + REQUIRE(context.treatment("exp_arity_2to3_a") == NORMAL_VARIANT); + + context.refresh(data_of({new_three_arm_holdout(31, "holdout_arity", THREE_ARM_1_SEED_LO)}, + {covered_by(new_experiment(1, "exp_arity_2to3_a"), {31}), + covered_by(new_experiment(2, "exp_arity_2to3_b"), {31})})); + + REQUIRE(context.treatment("exp_arity_2to3_b") == NORMAL_VARIANT); + require_published(context, {own_exposure(1, "exp_arity_2to3_a", NORMAL_VARIANT), + holdout_exposure(31, "holdout_arity", 1), + own_exposure(2, "exp_arity_2to3_b", NORMAL_VARIANT)}); +} + +TEST_CASE("Holdouts: a same-iteration 3 to 2 arm change keeps arm 1's 3-arm meaning", "[holdouts][refresh][arms]") { + Context context(config_with(UID), data_of({new_three_arm_holdout(41, "holdout_arity_rev", THREE_ARM_1_SEED_LO)}, + {covered_by(new_experiment(1, "exp_arity_3to2_a"), {41})})); + + REQUIRE(context.treatment("exp_arity_3to2_a") == 0); + REQUIRE(context.pending() == 1); + + context.refresh(data_of({new_holdout(41, "holdout_arity_rev", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {covered_by(new_experiment(1, "exp_arity_3to2_a"), {41}), + covered_by(new_experiment(2, "exp_arity_3to2_b"), {41})})); + + REQUIRE(context.treatment("exp_arity_3to2_b") == 0); + require_published(context, {holdout_exposure(41, "holdout_arity_rev", 1)}); +} + +TEST_CASE("Holdouts: experiments evaluated before and after a same-iteration arity change agree", + "[holdouts][refresh][arms]") { + Context context(config_with(UID), + data_of({new_holdout(71, "holdout_arity_consistency", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {covered_by(new_experiment(1, "exp_arity_consistency_pre"), {71})})); + + REQUIRE(context.treatment("exp_arity_consistency_pre") == NORMAL_VARIANT); + + context.refresh(data_of({new_three_arm_holdout(71, "holdout_arity_consistency", THREE_ARM_1_SEED_LO)}, + {covered_by(new_experiment(1, "exp_arity_consistency_pre"), {71}), + covered_by(new_experiment(2, "exp_arity_consistency_post"), {71})})); + + REQUIRE(context.treatment("exp_arity_consistency_post") == NORMAL_VARIANT); + REQUIRE(context.treatment("exp_arity_consistency_pre") == NORMAL_VARIANT); +} + +TEST_CASE("Holdouts: a refresh between the decision and the holdout trigger publishes the decision's epoch", + "[holdouts][refresh]") { + auto iteration_2 = new_holdout(11, "holdout_h", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO); + iteration_2.iteration = 2; + const auto refreshed = data_of({iteration_2}, {covered_by(new_experiment(1, "exp_epoch_race"), {11})}); + + auto logger = std::make_shared(); + logger->on_exposure = [&](Context& context, const json& data) { + if (data["id"] == 1) context.refresh(refreshed); + }; + Context context(config_with(UID), + data_of({new_holdout(11, "holdout_h", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {covered_by(new_experiment(1, "exp_epoch_race"), {11})}), + logger); + + REQUIRE(context.treatment("exp_epoch_race") == NORMAL_VARIANT); + require_published(context, {own_exposure(1, "exp_epoch_race", NORMAL_VARIANT), holdout_exposure(11, "holdout_h", 1)}); +} + +// --- Late units --------------------------------------------------------------------------------- + +TEST_CASE("Holdouts: set_unit evicts an unresolved holdout pin so its exposure is not lost", "[holdouts][late-unit]") { + Context context(ContextConfig{}, + data_of({new_holdout(11, "holdout_user_id", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO, "user_id")}, + {covered_by(new_experiment(1, "exp_null_snapshot_fullon", "user_id", 2), {11})})); + + REQUIRE(context.peek("exp_null_snapshot_fullon") == 2); + context.set_unit("user_id", UID); + + REQUIRE(context.treatment("exp_null_snapshot_fullon") == 2); + REQUIRE(context.pending() == 2); + + Expected own = own_exposure(1, "exp_null_snapshot_fullon", 2, "user_id"); + own.full_on = true; + require_published(context, {own, holdout_exposure(11, "holdout_user_id", 1, "user_id")}, {{"user_id", UID}}); +} + +TEST_CASE("Holdouts: set_unit keeps an exposed assignment, so there is no duplicate exposure", "[holdouts][late-unit]") { + Context context(ContextConfig{}, + data_of({new_holdout(11, "holdout_user_id", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO, "user_id")}, + {covered_by(new_experiment(1, "exp_exposed_before_unit", "user_id", 2), {11})})); + + REQUIRE(context.treatment("exp_exposed_before_unit") == 2); + REQUIRE(context.pending() == 1); + + context.set_unit("user_id", UID); + + REQUIRE(context.treatment("exp_exposed_before_unit") == 2); + REQUIRE(context.pending() == 1); +} + +TEST_CASE("Holdouts: set_unit of an unrelated unit type evicts nothing", "[holdouts][late-unit]") { + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {covered_by(new_experiment(1, "exp_unrelated_unit"), {11})})); + + REQUIRE(context.treatment("exp_unrelated_unit") == NORMAL_VARIANT); + REQUIRE(context.pending() == 2); + + context.set_unit("other_unit_type", "some-other-uid"); + + REQUIRE(context.treatment("exp_unrelated_unit") == NORMAL_VARIANT); + REQUIRE(context.pending() == 2); +} + +TEST_CASE("Holdouts: set_unit evicts only the affected assignment", "[holdouts][late-unit]") { + Context context(config_with(UID), + data_of({new_holdout(11, "holdout_late", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO, "user_id"), + new_holdout(12, "holdout_present", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {covered_by(new_experiment(1, "exp_late_unit", "user_id", 2), {11}), + covered_by(new_experiment(2, "exp_present_unit"), {12})})); + + REQUIRE(context.peek("exp_late_unit") == 2); + REQUIRE(context.treatment("exp_present_unit") == NORMAL_VARIANT); + REQUIRE(context.pending() == 2); + + context.set_unit("user_id", UID); + + REQUIRE(context.treatment("exp_late_unit") == 2); + REQUIRE(context.pending() == 4); + REQUIRE(context.treatment("exp_present_unit") == NORMAL_VARIANT); + REQUIRE(context.pending() == 4); +} + +TEST_CASE("Holdouts: set_unit evicts by the covered experiment's unit type, not the holdout's", "[holdouts][late-unit]") { + Context context(ContextConfig{}, + data_of({new_holdout(11, "holdout_declares_b", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO, "B")}, + {covered_by(new_experiment(1, "exp_mismatched_unit_type", "A", 2), {11})})); + + REQUIRE(context.peek("exp_mismatched_unit_type") == 2); + context.set_unit("A", UID); + + REQUIRE(context.treatment("exp_mismatched_unit_type") == 2); + REQUIRE(context.pending() == 2); +} + +TEST_CASE("Holdouts: set_unit re-resolves suppression when the late holdout holds the unit out", "[holdouts][late-unit]") { + Context context(ContextConfig{}, + data_of({new_holdout(11, "holdout_user_id_suppress", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO, "user_id")}, + {covered_by(new_experiment(1, "exp_null_snapshot_suppresses", "user_id", 2), {11})})); + + REQUIRE(context.peek("exp_null_snapshot_suppresses") == 2); + context.set_unit("user_id", UID); + + REQUIRE(context.treatment("exp_null_snapshot_suppresses") == 0); + REQUIRE(context.pending() == 1); + require_published(context, {holdout_exposure(11, "holdout_user_id_suppress", 0, "user_id")}, {{"user_id", UID}}); +} + +// Java's detachedTreatment*/settleExposure/retire tests exercise its lock-free exposure CAS and +// the retry of a "detached" Assignment replaced under a concurrent reader. The C++ Context is +// not thread-safe and has no detached assignments; the closest reachable case is an assignment +// replaced while an event logger runs. These pin the observable outcomes of those tests. + +TEST_CASE("Holdouts: a replaced assignment cannot publish beside a suppressing replacement", "[holdouts][late-unit]") { + // detachedTreatmentAssignmentCannotPublishBesideSuppressingReplacement + Context context(ContextConfig{}, + data_of({new_holdout(11, "holdout_detached_suppressed", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO, "user_id")}, + {covered_by(new_experiment(1, "exp_detached_suppressed", "user_id", 2), {11})})); + + REQUIRE(context.peek("exp_detached_suppressed") == 2); + context.set_unit("user_id", UID); + REQUIRE(context.treatment("exp_detached_suppressed") == 0); + REQUIRE(context.pending() == 1); + REQUIRE(context.treatment("exp_detached_suppressed") == 0); + REQUIRE(context.pending() == 1); + require_published(context, {holdout_exposure(11, "holdout_detached_suppressed", 0, "user_id")}, {{"user_id", UID}}); +} + +TEST_CASE("Holdouts: a replaced assignment's exposure is not lost or duplicated", "[holdouts][late-unit]") { + // detachedTreatmentAssignmentRetriesCurrentEntryWithoutLosingExposure + Context context(ContextConfig{}, + data_of({new_holdout(11, "holdout_detached_retry", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO, "user_id")}, + {covered_by(new_experiment(1, "exp_detached_retry", "user_id", 2), {11})})); + + REQUIRE(context.peek("exp_detached_retry") == 2); + context.set_unit("user_id", UID); + REQUIRE(context.treatment("exp_detached_retry") == 2); + REQUIRE(context.pending() == 2); + REQUIRE(context.treatment("exp_detached_retry") == 2); + REQUIRE(context.pending() == 2); + + Expected own = own_exposure(1, "exp_detached_retry", 2, "user_id"); + own.full_on = true; + require_published(context, {own, holdout_exposure(11, "holdout_detached_retry", 1, "user_id")}, {{"user_id", UID}}); +} + +TEST_CASE("Holdouts: treatment returns the re-resolved variant after a late unit", "[holdouts][late-unit]") { + // detachedTreatmentReturnsTheReplacementVariant + Context context(ContextConfig{}, + data_of({new_holdout(11, "holdout_detached_variant", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO, "user_id")}, + {covered_by(new_experiment(1, "exp_detached_variant", "user_id", 2), {11})})); + + REQUIRE(context.peek("exp_detached_variant") == 2); + context.set_unit("user_id", UID); + REQUIRE(context.treatment("exp_detached_variant") == 0); + REQUIRE(context.pending() == 1); +} + +TEST_CASE("Holdouts: an assignment replaced while the logger runs settles on one exposure", "[holdouts][late-unit]") { + // treatmentExposureSettlesAfterTwoConsecutiveRetirements and + // exposureSettlementStopsAfterTheBoundedNumberOfRetirements: a logger that replaces the + // assignment (here by a refresh changing the holdout coverage) mid-exposure neither loses + // nor repeats the exposure that was already queued, and never loops. + const auto refreshed = data_of({new_holdout(11, "holdout_a", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {covered_by(new_experiment(1, "exp_settled", 1), {11})}); + auto logger = std::make_shared(); + int refreshes = 0; + logger->on_exposure = [&](Context& context, const json&) { + if (refreshes++ < 2) context.refresh(refreshed); + }; + Context context(config_with(UID), data_of({}, {new_experiment(1, "exp_settled", 1)}), logger); + + REQUIRE(context.treatment("exp_settled") == 1); + REQUIRE(context.pending() == 1); + // The refreshed coverage is a new decision: the experiment and its holdout publish once each. + REQUIRE(context.treatment("exp_settled") == 1); + REQUIRE(context.treatment("exp_settled") == 1); + REQUIRE(context.pending() == 3); +} + +TEST_CASE("Holdouts: a variable key re-resolves to a new winner after a late unit and refresh", + "[holdouts][late-unit][variables]") { + // detachedVariableAssignmentReresolvesTheKeyToANewWinningExperiment + auto original = covered_by(new_experiment(2, "exp_detached_variable_old", "user_id", 1), {11}); + original.variants[1].config = R"({"detached_var":"old"})"; + const auto holdout = new_holdout(11, "holdout_detached_variable", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO, "user_id"); + Context context(ContextConfig{}, data_of({holdout}, {original})); + + REQUIRE(context.peek_variable_value("detached_var", "default") == "old"); + context.set_unit("user_id", UID); + + auto winner = covered_by(new_experiment(1, "exp_detached_variable_winner", "user_id", 1), {11}); + winner.variants[1].config = R"({"detached_var":"new winner"})"; + context.refresh(data_of({holdout}, {winner, original})); + + REQUIRE(context.variable_value("detached_var", "default") == "new winner"); + REQUIRE(context.pending() == 2); + REQUIRE(context.variable_value("detached_var", "default") == "new winner"); + REQUIRE(context.pending() == 2); + + Expected own = own_exposure(1, "exp_detached_variable_winner", 1, "user_id"); + own.full_on = true; + require_published(context, {holdout_exposure(11, "holdout_detached_variable", 1, "user_id"), own}, + {{"user_id", UID}}); +} + +TEST_CASE("Holdouts: an exposed assignment's unresolved pin is never resolved live later", "[holdouts][late-unit]") { + auto experiment = covered_by(new_experiment(1, "exp_a_mutant_pinned_null", "user_id", 1), {11}); + experiment.variants[1].config = R"({"my_var":"value_from_variant"})"; + Context context(ContextConfig{}, + data_of({new_holdout(11, "holdout_a_mutant_pinned_null", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO, + "user_id")}, + {experiment})); + + REQUIRE(context.treatment("exp_a_mutant_pinned_null") == 1); + REQUIRE(context.pending() == 1); + + context.set_unit("user_id", UID); + + REQUIRE(context.variable_value("my_var", "default") == "value_from_variant"); + REQUIRE(context.pending() == 1); +} + +TEST_CASE("Holdouts: set_unit evicts an assignment whose holdouts declare other unit types", "[holdouts][late-unit]") { + Context context(ContextConfig{}, + data_of({new_holdout(11, "holdout_11", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO, "type_x"), + new_holdout(12, "holdout_12", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO, "type_y"), + new_holdout(13, "holdout_13", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO, "user_id")}, + {covered_by(new_experiment(1, "exp_multi_holdout_unit_types", "user_id", 2), {11, 12, 13})})); + + REQUIRE(context.peek("exp_multi_holdout_unit_types") == 2); + context.set_unit("user_id", UID); + + REQUIRE(context.treatment("exp_multi_holdout_unit_types") == 2); + REQUIRE(context.pending() == 4); +} + +TEST_CASE("Holdouts: one holdout over two unit types keeps an exposure state per unit type", "[holdouts][exposure]") { + ContextConfig config; + config.units = {{"user_id", UID}, {"session_id", UID}}; + Context context(config, data_of({new_holdout(11, "holdout_shared", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO, "user_id")}, + {covered_by(new_experiment(1, "exp_unit_a1", "user_id", 0), {11}), + covered_by(new_experiment(2, "exp_unit_b", "session_id", 0), {11}), + covered_by(new_experiment(3, "exp_unit_a2", "user_id", 0), {11})})); + + REQUIRE(context.treatment("exp_unit_a1") == NORMAL_VARIANT); + REQUIRE(context.treatment("exp_unit_b") == NORMAL_VARIANT); + REQUIRE(context.treatment("exp_unit_a2") == NORMAL_VARIANT); + REQUIRE(context.pending() == 5); + + const auto event = context.publish(); + std::vector holdout_units; + for (const auto& exposure : event.exposures) { + if (exposure.id == 11) holdout_units.push_back(exposure.unit); + } + REQUIRE(holdout_units == std::vector{"user_id", "session_id"}); +} + +TEST_CASE("Holdouts: set_unit with nothing cached assigns normally", "[holdouts][late-unit]") { + Context context(ContextConfig{}, data_of({new_holdout(11, "holdout_a", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {covered_by(new_experiment(1, "exp_no_prior_assignment"), {11})})); + + REQUIRE_NOTHROW(context.set_unit(UNIT_TYPE, UID)); + REQUIRE(context.treatment("exp_no_prior_assignment") == NORMAL_VARIANT); +} + +TEST_CASE("Holdouts: set_unit with the same uid again is a no-op", "[holdouts][late-unit]") { + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {covered_by(new_experiment(1, "exp_set_unit_twice"), {11})})); + + REQUIRE(context.treatment("exp_set_unit_twice") == NORMAL_VARIANT); + REQUIRE(context.pending() == 2); + + REQUIRE_NOTHROW(context.set_unit(UNIT_TYPE, UID)); + + REQUIRE(context.treatment("exp_set_unit_twice") == NORMAL_VARIANT); + REQUIRE(context.pending() == 2); +} + +TEST_CASE("Holdouts: a redundant set_unit does not evict a fully resolved unexposed assignment", + "[holdouts][late-unit]") { + // A same-iteration split change is invisible to the cache check, so a wrongly evicted + // assignment would re-resolve to variant 0. + const auto holdout = new_holdout(11, "holdout_a", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO); + Context context(config_with(UID), data_of({holdout}, {covered_by(new_experiment(1, "exp_redundant_set_unit"), {11})})); + + REQUIRE(context.peek("exp_redundant_set_unit") == NORMAL_VARIANT); + REQUIRE(context.pending() == 0); + + auto refreshed = covered_by(new_experiment(1, "exp_redundant_set_unit"), {11}); + refreshed.split = {1.0, 0.0}; + context.refresh(data_of({holdout}, {refreshed})); + + context.set_unit(UNIT_TYPE, UID); + + REQUIRE(context.treatment("exp_redundant_set_unit") == NORMAL_VARIANT); + require_published(context, {own_exposure(1, "exp_redundant_set_unit", NORMAL_VARIANT), + holdout_exposure(11, "holdout_a", 1)}); +} + +TEST_CASE("Holdouts: peek_variable_value, a late unit, then variable_value re-resolves under a suppressing holdout", + "[holdouts][late-unit][variables]") { + auto experiment = covered_by(new_experiment(1, "exp_var_late_unit_suppress", "user_id", 1), {11}); + experiment.variants[1].config = R"({"my_var":"value_from_variant"})"; + Context context(ContextConfig{}, + data_of({new_holdout(11, "holdout_var_late", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO, "user_id")}, + {experiment})); + + REQUIRE(context.peek_variable_value("my_var", "default") == "value_from_variant"); + REQUIRE(context.pending() == 0); + + context.set_unit("user_id", UID); + + REQUIRE(context.variable_value("my_var", "default") == "default"); + REQUIRE(context.pending() == 1); + require_published(context, {holdout_exposure(11, "holdout_var_late", 0, "user_id")}, {{"user_id", UID}}); +} + +TEST_CASE("Holdouts: an override peeked before its unit still publishes the holdout once the unit is set", + "[holdouts][late-unit]") { + ContextConfig config; + config.overrides["exp_override_late_unit"] = 3; + Context context(config, + data_of({new_holdout(11, "holdout_override_late", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO, "user_id")}, + {covered_by(new_experiment(1, "exp_override_late_unit", "user_id", 0), {11})})); + + REQUIRE(context.peek("exp_override_late_unit") == 3); + context.set_unit("user_id", UID); + + REQUIRE(context.treatment("exp_override_late_unit") == 3); + REQUIRE(context.pending() == 2); + + Expected own = own_exposure(1, "exp_override_late_unit", 3, "user_id"); + own.assigned = false; + own.overridden = true; + require_published(context, {own, holdout_exposure(11, "holdout_override_late", 1, "user_id")}, {{"user_id", UID}}); +} + +TEST_CASE("Holdouts: a custom assignment applies after a late unit re-resolves the assignment", "[holdouts][late-unit]") { + ContextConfig config; + config.custom_assignments["exp_custom_late_unit"] = 3; + Context context(config, + data_of({new_holdout(11, "holdout_custom_late", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO, "user_id")}, + {covered_by(new_experiment(1, "exp_custom_late_unit", "user_id", 0), {11})})); + + REQUIRE(context.peek("exp_custom_late_unit") == 0); + context.set_unit("user_id", UID); + + REQUIRE(context.treatment("exp_custom_late_unit") == 3); + REQUIRE(context.pending() == 2); + + Expected own = own_exposure(1, "exp_custom_late_unit", 3, "user_id"); + own.custom = true; + require_published(context, {own, holdout_exposure(11, "holdout_custom_late", 1, "user_id")}, {{"user_id", UID}}); +} + +// --- Cross-SDK verdict vectors (java-sdk, checked against the collector) ---------------------- + +namespace { + +const char* VERDICT_UNIT_TYPE = "verdict_unit_type"; + +HoldoutData verdict_holdout(int id, int32_t seed_hi, int32_t seed_lo, std::vector split) { + auto holdout = new_holdout(id, "holdout_" + std::to_string(id), seed_hi, seed_lo, VERDICT_UNIT_TYPE); + holdout.split = std::move(split); + return holdout; +} + +std::unique_ptr verdict_context(const std::string& uid, const std::vector& holdouts) { + std::vector ids; + for (const auto& holdout : holdouts) ids.push_back(holdout.id); + return std::make_unique( + config_with(uid, VERDICT_UNIT_TYPE), + data_of(holdouts, {covered_by(new_experiment(9, "verdict_vectors_experiment", VERDICT_UNIT_TYPE, 0), ids)})); +} + +void require_held_out_by(const std::string& uid, const HoldoutData& holdout) { + auto context = verdict_context(uid, {holdout}); + REQUIRE(context->treatment("verdict_vectors_experiment") == 0); + const auto event = context->publish(); + REQUIRE(event.exposures.size() == 1); + REQUIRE(event.exposures[0].id == holdout.id); + REQUIRE(event.exposures[0].name == holdout.name); + REQUIRE(event.exposures[0].variant == 0); +} + +void require_not_held_out(const std::string& uid, const HoldoutData& holdout) { + auto context = verdict_context(uid, {holdout}); + context->treatment("verdict_vectors_experiment"); + const auto event = context->publish(); + REQUIRE(std::any_of(event.exposures.begin(), event.exposures.end(), [&](const Exposure& e) { + return e.id == holdout.id && e.name == holdout.name && e.variant == 1; + })); +} + +} // namespace + +TEST_CASE("Holdout verdicts: Unicode unit ids", "[holdouts][verdicts]") { + require_held_out_by("fa\xC3\xA7" "ade", verdict_holdout(107, 0, 42, {0.1, 0.9})); + require_not_held_out("unicode_emoji_\xF0\x9F\x9A\x80_0", verdict_holdout(107, 0, 42, {0.1, 0.9})); +} + +TEST_CASE("Holdout verdicts: seed halves with the sign bit set", "[holdouts][verdicts]") { + const int64_t seed = static_cast(0x8000000080000000ULL); + const auto seed_hi = static_cast(seed >> 32); + const auto seed_lo = static_cast(static_cast(seed & 0xffffffff)); + require_held_out_by("signed_unit_4", verdict_holdout(106, seed_hi, seed_lo, {0.1, 0.9})); + require_not_held_out("signed_unit_b_1", verdict_holdout(106, seed_hi, seed_lo, {0.1, 0.9})); +} + +TEST_CASE("Holdout verdicts: 1% boundary", "[holdouts][verdicts]") { + require_held_out_by("pct1_unit_188", verdict_holdout(105, 0, 999999, {0.01, 0.99})); + require_not_held_out("pct1_unit_0", verdict_holdout(105, 0, 999999, {0.01, 0.99})); +} + +TEST_CASE("Holdout verdicts: either side of the 10% boundary", "[holdouts][verdicts]") { + require_held_out_by("boundary_unit_175653", verdict_holdout(107, 0, 42, {0.1, 0.9})); + require_not_held_out("boundary_unit_75792", verdict_holdout(107, 0, 42, {0.1, 0.9})); +} + +TEST_CASE("Holdout verdicts: a unit held out by two holdouts at once", "[holdouts][verdicts]") { + auto context = verdict_context("dual_holdout_unit_5", {verdict_holdout(107, 0, 42, {0.1, 0.9}), + verdict_holdout(108, 0, 55, {0.1, 0.9})}); + REQUIRE(context->treatment("verdict_vectors_experiment") == 0); + require_published(*context, {holdout_exposure(107, "holdout_107", 0, VERDICT_UNIT_TYPE), + holdout_exposure(108, "holdout_108", 0, VERDICT_UNIT_TYPE)}, + {{VERDICT_UNIT_TYPE, "dual_holdout_unit_5"}}); +} + +// --- Variables ---------------------------------------------------------------------------------- + +TEST_CASE("Holdouts: variable_value publishes the holdout for held-out and not-held-out units", + "[holdouts][variables]") { + auto experiment = covered_by(new_experiment(1, "exp_var"), {11}); + experiment.variants[1].config = R"({"var_a":"value_a"})"; + const auto holdout = new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO); + + Context held_out(config_with(UID), data_of({holdout}, {experiment})); + REQUIRE(held_out.variable_value("var_a", "default") == "default"); + REQUIRE(held_out.pending() == 1); + + Context not_held_out(config_with(UID_NOT_HELD_OUT), data_of({holdout}, {experiment})); + REQUIRE(not_held_out.variable_value("var_a", "default") == "default"); + REQUIRE(not_held_out.pending() == 2); +} + +TEST_CASE("Holdouts: a variable key skips a suppressed experiment for an assigned one", "[holdouts][variables]") { + auto suppressed = covered_by(new_experiment(1, "exp_var_key_suppressed"), {11}); + suppressed.variants[1].config = R"({"shared":"from_suppressed"})"; + auto assigned = new_experiment(2, "exp_var_key_assigned"); + assigned.variants[1].config = R"({"shared":"from_assigned"})"; + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {suppressed, assigned})); + + REQUIRE(context.variable_value("shared", "default") == "from_assigned"); + require_published(context, {holdout_exposure(11, "holdout_a", 0), + own_exposure(2, "exp_var_key_assigned", NORMAL_VARIANT)}); +} + +TEST_CASE("Holdouts: peek_variable_value publishes nothing", "[holdouts][variables][peek]") { + auto suppressed = covered_by(new_experiment(1, "exp_var_key_peek_suppressed"), {11}); + suppressed.variants[1].config = R"({"shared_peek":"from_suppressed"})"; + auto assigned = new_experiment(2, "exp_var_key_peek_assigned"); + assigned.variants[1].config = R"({"shared_peek":"from_assigned"})"; + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {suppressed, assigned})); + + REQUIRE(context.peek_variable_value("shared_peek", "default") == "from_assigned"); + REQUIRE(context.pending() == 0); +} + +TEST_CASE("Holdouts: a suppressed experiment's variable reads its control value, not the default", + "[holdouts][variables]") { + // Scenario 226: a held-out unit sees control, as the experiment would show it. + auto experiment = with_variables(covered_by(new_experiment(1, "exp_held_out"), {11}), "color"); + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {experiment})); + + REQUIRE(context.peek_variable_value("color", "default") == "control"); + REQUIRE(context.variable_value("color", "default") == "control"); + require_published(context, {holdout_exposure(11, "holdout_a", 0)}); +} + +// --- Event logger --------------------------------------------------------------------------------- + +TEST_CASE("Holdouts: a throwing logger does not lose a sibling holdout exposure", "[holdouts][logger]") { + auto logger = std::make_shared(); + logger->throws_on = [](const json& data) { return data["id"] == 11; }; + Context context(config_with(UID), + data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO), + new_holdout(12, "holdout_b", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {covered_by(new_experiment(1, "exp_multi_holdout_throwing_logger"), {11, 12})}), + logger); + + // The C++ SDK never lets a logger exception reach the caller. + REQUIRE(context.treatment("exp_multi_holdout_throwing_logger") == 0); + REQUIRE(context.pending() == 2); +} + +TEST_CASE("Holdouts: a throwing logger does not make an exposure retryable", "[holdouts][logger]") { + auto logger = std::make_shared(); + logger->throws_on = [](const json& data) { return data["id"] == 1; }; + Context context(config_with(UID), data_of({new_holdout(11, "holdout_terminal", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {covered_by(new_experiment(1, "exp_throwing_logger_terminal"), {11})}), + logger); + + REQUIRE(context.treatment("exp_throwing_logger_terminal") == NORMAL_VARIANT); + logger->throws_on = [](const json&) { return false; }; + REQUIRE(context.treatment("exp_throwing_logger_terminal") == NORMAL_VARIANT); + require_published(context, {own_exposure(1, "exp_throwing_logger_terminal", NORMAL_VARIANT), + holdout_exposure(11, "holdout_terminal", 1)}); +} + +TEST_CASE("Holdouts: a throwing logger still queues a suppressed experiment's only holdout exposure", + "[holdouts][logger]") { + // Java checks a flush is scheduled; the C++ Context publishes on demand, so the exposure + // must be pending and published. + auto logger = std::make_shared(); + logger->throws_on = [](const json&) { return true; }; + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_stranded_flush"), {11})}), + logger); + + REQUIRE(context.treatment("exp_stranded_flush") == 0); + REQUIRE(context.pending() == 1); + require_published(context, {holdout_exposure(11, "holdout_a", 0)}); +} + +// --- Malformed holdouts ------------------------------------------------------------------------- + +TEST_CASE("Holdouts: a null holdouts entry is ignored", "[holdouts][malformed]") { + const auto data = json::parse(R"({"experiments":[],"holdouts":[null]})").get(); + auto with_experiment = data; + with_experiment.experiments.push_back(new_experiment(1, "exp_null_holdout_entry")); + Context context(config_with(UID), with_experiment); + + REQUIRE(context.treatment("exp_null_holdout_entry") == NORMAL_VARIANT); + require_published(context, {own_exposure(1, "exp_null_holdout_entry", NORMAL_VARIANT)}); +} + +TEST_CASE("Holdouts: a holdout without a split is ignored", "[holdouts][malformed]") { + for (const char* split : {"null", "[]", "absent"}) { + json holdout = {{"id", 11}, {"name", "holdout_no_split"}, {"iteration", 1}, {"unitType", UNIT_TYPE}, + {"seedHi", HOLDOUT_A_SEED_HI}, {"seedLo", HOLDOUT_A_SEED_LO}}; + if (std::string(split) != "absent") holdout["split"] = json::parse(split); + auto data = json({{"experiments", json::array()}, {"holdouts", json::array({holdout})}}).get(); + data.experiments.push_back(covered_by(new_experiment(1, "exp_no_split_holdout"), {11})); + Context context(config_with(UID), data); + + REQUIRE(context.treatment("exp_no_split_holdout") == NORMAL_VARIANT); + require_published(context, {own_exposure(1, "exp_no_split_holdout", NORMAL_VARIANT)}); + } +} + +// --- Refresh with overrides --------------------------------------------------------------------- + +TEST_CASE("Holdouts: an epoch already exposed is not exposed again by an older experiment's pin", + "[holdouts][refresh]") { + // staleHoldoutReferenceNeverOverwritesNewerPinnedCacheEntry: Java calls a private trigger + // with a stale holdout; here every reachable path resolves the live definition by id, so + // re-evaluating the experiment pinned to iteration 1 after G exposed iteration 2 must not + // expose iteration 2 again. + Context context(config_with(UID), data_of({new_holdout(11, "holdout_h", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_f"), {11})})); + + REQUIRE(context.treatment("exp_f") == 0); + REQUIRE(context.pending() == 1); + + auto iteration_2 = new_holdout(11, "holdout_h", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO); + iteration_2.iteration = 2; + context.refresh(data_of({iteration_2}, {covered_by(new_experiment(1, "exp_f"), {11}), + covered_by(new_experiment(2, "exp_g"), {11})})); + + REQUIRE(context.treatment("exp_g") == NORMAL_VARIANT); + REQUIRE(context.pending() == 3); + + // exp_f is re-resolved against iteration 2: no longer held out, so it publishes its own + // exposure, but the holdout's iteration 2 exposure is not repeated. + REQUIRE(context.treatment("exp_f") == NORMAL_VARIANT); + require_published(context, {holdout_exposure(11, "holdout_h", 0), own_exposure(2, "exp_g", NORMAL_VARIANT), + holdout_exposure(11, "holdout_h", 1), own_exposure(1, "exp_f", NORMAL_VARIANT)}); +} + +TEST_CASE("Holdouts: a holdout added by a refresh fires for an overridden experiment", "[holdouts][refresh]") { + auto config = config_with(UID); + config.overrides["exp_override_late_holdout"] = 3; + Context context(config, data_of({}, {new_experiment(1, "exp_override_late_holdout")})); + + REQUIRE(context.treatment("exp_override_late_holdout") == 3); + REQUIRE(context.pending() == 1); + + context.refresh(data_of({new_holdout(11, "holdout_late", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_override_late_holdout"), {11})})); + + REQUIRE(context.treatment("exp_override_late_holdout") == 3); + REQUIRE(context.pending() == 3); + + Expected own = own_exposure(1, "exp_override_late_holdout", 3); + own.assigned = false; + own.overridden = true; + require_published(context, {own, own, holdout_exposure(11, "holdout_late", 0)}); +} + +TEST_CASE("Holdouts: a holdout exposure from the variable path is published", "[holdouts][variables]") { + // variablePathHoldoutExposureSchedulesFlushWithoutAnyOtherEvent: no scheduler in C++. + auto suppressed = covered_by(new_experiment(1, "exp_var_flush_suppressed"), {11}); + suppressed.variants[1].config = R"({"flush_key":"from_suppressed"})"; + auto assigned = new_experiment(2, "exp_var_flush_assigned"); + assigned.variants[1].config = R"({"flush_key":"from_assigned"})"; + Context context(config_with(UID), data_of({new_holdout(11, "holdout_flush", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {suppressed, assigned})); + + REQUIRE(context.treatment("exp_var_flush_assigned") == NORMAL_VARIANT); + REQUIRE(context.pending() == 1); + REQUIRE(context.variable_value("flush_key", "default") == "from_assigned"); + REQUIRE(context.pending() == 2); +} + +TEST_CASE("Holdouts: installing data does not change the caller's holdoutIds", "[holdouts]") { + auto covered = new_experiment(1, "exp_holdout_no_mutate_in"); + covered.holdoutIds = {12, 11}; + const auto data = data_of({new_holdout(11, "holdout_no_mutate", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered, new_experiment(2, "exp_holdout_no_mutate_not_covered")}); + Context context(config_with(UID), data); + + REQUIRE(context.treatment("exp_holdout_no_mutate_in") == 0); + REQUIRE(context.treatment("exp_holdout_no_mutate_not_covered") == NORMAL_VARIANT); + REQUIRE(data.experiments[0].holdoutIds == std::vector{12, 11}); + REQUIRE(context.data().experiments[0].holdoutIds == std::vector{12, 11}); +} + +// --- Assignment rules (scenario 305) ------------------------------------------------------------ + +TEST_CASE("Holdouts: a matching assign rule wins over suppression and the holdout still publishes", + "[holdouts][rules]") { + auto experiment = covered_by(new_experiment(1, "exp_holdout_rules"), {11}); + experiment.assignmentRules = US_RULE; + Context context(config_with(UID), + data_of({new_holdout(11, "holdout_rules_suppression", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {experiment})); + context.set_attribute("country", "US"); + + REQUIRE(context.treatment("exp_holdout_rules") == 1); + + Expected own = own_exposure(1, "exp_holdout_rules", 1); + own.assigned = false; + own.rule_override = true; + require_published(context, {own, holdout_exposure(11, "holdout_rules_suppression", 0)}); +} + +TEST_CASE("Holdouts: a matching split rule wins over suppression", "[holdouts][rules]") { + auto experiment = covered_by(new_experiment(1, "exp_holdout_split_rule"), {11}); + experiment.assignmentRules = + R"({"rules":[{"name":"Everyone","type":"split","conditions":null,"environments":[],"percentages":"0/100"}]})"; + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {experiment})); + + REQUIRE(context.peek("exp_holdout_split_rule") == 1); + REQUIRE(context.treatment("exp_holdout_split_rule") == 1); + REQUIRE(context.pending() == 2); +} + +TEST_CASE("Holdouts: a held-out unit is suppressed until a rule matches", "[holdouts][rules]") { + auto experiment = covered_by(new_experiment(1, "exp_holdout_rules"), {11}); + experiment.assignmentRules = US_RULE; + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {experiment})); + context.set_attribute("country", "GB"); + + REQUIRE(context.treatment("exp_holdout_rules") == 0); + REQUIRE(context.pending() == 1); + + context.set_attribute("country", "US"); + REQUIRE(context.treatment("exp_holdout_rules") == 1); + REQUIRE(context.pending() == 2); +} + +TEST_CASE("Holdouts: a held-out unit is suppressed again when the rule stops matching", "[holdouts][rules]") { + auto experiment = covered_by(new_experiment(1, "exp_holdout_rules"), {11}); + experiment.assignmentRules = US_RULE; + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {experiment})); + context.set_attribute("country", "US"); + + REQUIRE(context.treatment("exp_holdout_rules") == 1); + REQUIRE(context.pending() == 2); + + context.set_attribute("country", "GB"); + REQUIRE(context.treatment("exp_holdout_rules") == 0); + REQUIRE(context.peek("exp_holdout_rules") == 0); + REQUIRE(context.pending() == 2); +} + +TEST_CASE("Holdouts: variable_value on a held-out, rule-won experiment", "[holdouts][rules][variables]") { + auto experiment = with_variables(covered_by(new_experiment(1, "exp_holdout_rules"), {11}), "color"); + experiment.assignmentRules = US_RULE; + Context context(config_with(UID), + data_of({new_holdout(11, "holdout_rules_suppression", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {experiment})); + context.set_attribute("country", "US"); + + REQUIRE(context.variable_value("color", "default") == "treatment"); + + Expected own = own_exposure(1, "exp_holdout_rules", 1); + own.assigned = false; + own.rule_override = true; + require_published(context, {holdout_exposure(11, "holdout_rules_suppression", 0), own}); +} + +TEST_CASE("Holdouts: a shared variable key prefers a rule-won experiment over a suppressed one", + "[holdouts][rules][variables]") { + auto held_out = with_variables(covered_by(new_experiment(1, "exp_held_out"), {11}), "color"); + auto rule_won = with_variables(covered_by(new_experiment(2, "exp_rule_won"), {11}), "color"); + rule_won.assignmentRules = US_RULE; + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {held_out, rule_won})); + + context.set_attribute("country", "GB"); + REQUIRE(context.peek_variable_value("color", "default") == "control"); + + context.set_attribute("country", "US"); + REQUIRE(context.peek_variable_value("color", "default") == "treatment"); +} + +TEST_CASE("Holdouts: a shared variable key prefers an earlier assigned experiment over a later rule-won one", + "[holdouts][rules][variables]") { + auto assigned = with_variables(new_experiment(1, "exp_assigned"), "color"); + assigned.split = {1.0, 0.0}; + auto rule_won = with_variables(new_experiment(2, "exp_rule_won"), "color"); + rule_won.assignmentRules = US_RULE; + Context context(config_with(UID), data_of({}, {assigned, rule_won})); + context.set_attribute("country", "US"); + + REQUIRE(context.peek_variable_value("color", "default") == "control"); + REQUIRE(context.peek("exp_rule_won") == 1); +} + +// --- Shared holdout scenarios H1-H8 (cross-sdk-tests) --------------------------------------------- + +TEST_CASE("Holdouts H1: a duplicate holdout id publishes one holdout exposure", "[holdouts][conformance]") { + // javascript-sdk dedups holdoutIds (insertUniqueSorted). + Context context(config_with(UID_NOT_HELD_OUT), + data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_duplicate_ids"), {11, 11})})); + + REQUIRE(context.treatment("exp_duplicate_ids") == 0); + require_published(context, {own_exposure(1, "exp_duplicate_ids", 0), holdout_exposure(11, "holdout_a", 1)}, + {{UNIT_TYPE, UID_NOT_HELD_OUT}}); +} + +TEST_CASE("Holdouts H1: duplicate and unsorted ids resolve once each, in id order", "[holdouts][conformance]") { + Context context(config_with(UID), + data_of({new_holdout(12, "holdout_b", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO), + new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_unsorted_ids"), {12, 11, 12, 999, 11})})); + + REQUIRE(context.treatment("exp_unsorted_ids") == 0); + require_published(context, {holdout_exposure(11, "holdout_a", 0), holdout_exposure(12, "holdout_b", 1)}); +} + +TEST_CASE("Holdouts H4: peek on a covered experiment queues nothing", "[holdouts][conformance][peek]") { + for (const char* uid : {UID, UID_NOT_HELD_OUT}) { + Context context(config_with(uid), data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_peek"), {11})})); + context.peek("exp_peek"); + context.peek("exp_peek"); + REQUIRE(context.pending() == 0); + + context.treatment("exp_peek"); + REQUIRE(context.pending() == (uid == UID ? 1 : 2)); + } +} + +TEST_CASE("Holdouts H7: a strict audience mismatch on a covered, not-held-out experiment still fires the holdout", + "[holdouts][conformance]") { + auto experiment = covered_by(new_experiment(1, "exp_strict_mismatch"), {11}); + experiment.audienceStrict = true; + experiment.audience = AGE_AUDIENCE; + Context context(config_with(UID_NOT_HELD_OUT), + data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, {experiment})); + context.set_attribute("age", 5); + + REQUIRE(context.treatment("exp_strict_mismatch") == 0); + + Expected own = own_exposure(1, "exp_strict_mismatch", 0); + own.assigned = false; + own.audience_mismatch = true; + const auto event = context.publish(); + REQUIRE(event.exposures.size() == 2); + REQUIRE(to_json_actual(event.exposures[0]) == to_json_expected(own)); + REQUIRE(to_json_actual(event.exposures[1]) == to_json_expected(holdout_exposure(11, "holdout_a", 1))); +} + +TEST_CASE("Holdouts H8: a shared key whose first candidate is suppressed and second assigned fires both holdouts", + "[holdouts][conformance][variables]") { + auto suppressed = with_variables(covered_by(new_experiment(1, "exp_first_suppressed"), {11}), "color"); + auto assigned = with_variables(covered_by(new_experiment(2, "exp_second_assigned"), {12}), "color"); + Context context(config_with(UID), + data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO), + new_holdout(12, "holdout_b", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {suppressed, assigned})); + + REQUIRE(context.variable_value("color", "default") == "treatment"); + // As in java-sdk: each candidate's holdouts as it is checked, then the winner's own exposure. + require_published(context, {holdout_exposure(11, "holdout_a", 0), holdout_exposure(12, "holdout_b", 1), + own_exposure(2, "exp_second_assigned", NORMAL_VARIANT)}); +} + +// --- Payload decoding and forward compatibility ------------------------------------------------- + +namespace { + +std::string read_fixture(const std::string& name) { + std::ifstream in(std::string(ABSMARTLY_TEST_FIXTURES_DIR) + "/" + name); + REQUIRE(in.good()); + std::stringstream buffer; + buffer << in.rdbuf(); + return buffer.str(); +} + +} // namespace + +TEST_CASE("Holdouts: the java-sdk holdouts_context.json fixture decodes", "[holdouts][json]") { + // Vendored byte-identical from java-sdk core-api/src/test/resources/holdouts_context.json + // (blob 92f1dbf4): one full-shape holdout and one slim one. + const auto data = json::parse(read_fixture("holdouts_context.json")).get(); + + REQUIRE(data.experiments.size() == 1); + REQUIRE(data.experiments[0].holdoutIds == std::vector{11}); + REQUIRE(data.experiments[0].holdoutType.empty()); + REQUIRE(data.holdouts.size() == 2); + + const auto& full = data.holdouts[0]; + REQUIRE(full.id == 11); + REQUIRE(full.name == "holdout_a"); + REQUIRE(full.unitType == "session_id"); + REQUIRE(full.iteration == 1); + REQUIRE(full.seedHi == 13); + REQUIRE(full.seedLo == 111); + REQUIRE(full.split == std::vector{0.1, 0.9}); + REQUIRE(full.holdoutType == "full"); + + const auto& slim = data.holdouts[1]; + REQUIRE(slim.id == 12); + REQUIRE(slim.name == "holdout_b"); + REQUIRE(slim.split == std::vector{0.05, 0.05, 0.9}); + REQUIRE(slim.holdoutType.empty()); + + Context context(config_with(UID), data); + REQUIRE(context.treatment("exp_test_holdout") == 0); + require_published(context, {holdout_exposure(11, "holdout_a", 0)}); +} + +TEST_CASE("Holdouts H5: unknown keys in holdout objects are ignored", "[holdouts][json][forward-compat]") { + // Unknown scalar, object and array keys inside each holdout, in the experiments and at the root, + // across two experiments: both still assign, and the context loads without an error event. + const auto data = json::parse(read_fixture("holdouts_forward_compat_context.json")).get(); + REQUIRE(data.holdouts.size() == 2); + REQUIRE(data.experiments.size() == 2); + + auto logger = std::make_shared(); + struct Errors : ContextEventLogger { + int count = 0; + void handle_event(Context&, const std::string& type, const json&) override { + if (type == "error") ++count; + } + }; + auto errors = std::make_shared(); + Context context(config_with(UID), data, errors); + + REQUIRE(context.treatment("exp_covered") == 0); + REQUIRE(context.treatment("exp_uncovered") == NORMAL_VARIANT); + REQUIRE(errors->count == 0); + require_published(context, {holdout_exposure(11, "holdout_future", 0), holdout_exposure(12, "holdout_slim", 1), + own_exposure(2, "exp_uncovered", NORMAL_VARIANT)}); +} + +TEST_CASE("Holdouts: malformed holdout entries and ids degrade only themselves", "[holdouts][json][forward-compat]") { + const auto data = json::parse(R"({ + "experiments": [ + {"id": 1, "name": "exp_a", "unitType": "session_id", "iteration": 1, "seedHi": 100, "seedLo": 200, + "split": [0.5, 0.5], "trafficSeedHi": 1, "trafficSeedLo": 2, "trafficSplit": [0, 1], + "fullOnVariant": 0, "variants": [{"name": "A", "config": null}, {"name": "B", "config": null}], + "holdoutIds": ["11", null, 11.5, 4294967307, 11.0, {"id": 11}, true]}, + {"id": 2, "name": "exp_b", "unitType": "session_id", "iteration": 1, "seedHi": 100, "seedLo": 200, + "split": [0.5, 0.5], "trafficSeedHi": 1, "trafficSeedLo": 2, "trafficSplit": [0, 1], + "fullOnVariant": 0, "variants": [{"name": "A", "config": null}, {"name": "B", "config": null}], + "holdoutIds": "11", "holdoutType": 3} + ], + "holdouts": [ + "not an object", 7, [], {"name": "no id"}, {"id": "11", "split": [0.1, 0.9]}, + {"id": 13, "name": "bad split", "split": [0.1, "0.9"], "seedHi": 13, "seedLo": 111}, + {"id": 11, "name": "holdout_a", "iteration": 1, "seedHi": 13, "seedLo": 111, "split": [0.1, 0.9], + "unitType": null, "holdoutType": null} + ] + })").get(); + + REQUIRE(data.experiments[0].holdoutIds == std::vector{11}); + REQUIRE(data.experiments[1].holdoutIds.empty()); + REQUIRE(data.experiments[1].holdoutType.empty()); + REQUIRE(data.holdouts.size() == 2); + REQUIRE(data.holdouts[0].id == 13); + REQUIRE(data.holdouts[0].split.empty()); + REQUIRE(data.holdouts[1].id == 11); + + Context context(config_with(UID), data); + REQUIRE(context.treatment("exp_a") == 0); + REQUIRE(context.treatment("exp_b") == NORMAL_VARIANT); +} + +TEST_CASE("Holdouts: a payload without holdouts serialises and publishes as before", "[holdouts][json][compat]") { + const json experiment = {{"id", 1}, {"name", "exp_plain"}, {"unitType", UNIT_TYPE}, {"iteration", 1}, + {"seedHi", NORMAL_SEED_HI}, {"seedLo", NORMAL_SEED_LO}, {"split", {0.5, 0.5}}, + {"trafficSeedHi", 1}, {"trafficSeedLo", 2}, {"trafficSplit", {0, 1}}, + {"fullOnVariant", 0}, {"variants", {{{"name", "A"}, {"config", nullptr}}, + {{"name", "B"}, {"config", R"({"k":1})"}}}}}; + std::vector payloads = {{{"experiments", {experiment}}}, + {{"experiments", {experiment}}, {"holdouts", json::array()}}, + {{"experiments", {experiment}}, {"holdouts", nullptr}}}; + + // to_json writes neither holdouts nor holdoutIds/holdoutType when there are none, so the + // re-serialised data has the keys it always had. + const json reserialised = payloads[0].get(); + REQUIRE_FALSE(reserialised.contains("holdouts")); + REQUIRE_FALSE(reserialised["experiments"][0].contains("holdoutIds")); + REQUIRE_FALSE(reserialised["experiments"][0].contains("holdoutType")); + + std::vector bodies; + for (const auto& payload : payloads) { + Context context(config_with(UID), payload.get()); + context.set_attribute("attr", "value"); + context.treatment("exp_plain"); + context.variable_value("k", 0); + context.track("goal", {{"amount", 1}}); + json body = context.publish(); + body["publishedAt"] = 0; + for (auto& e : body["exposures"]) e["exposedAt"] = 0; + for (auto& g : body["goals"]) g["achievedAt"] = 0; + for (auto& a : body["attributes"]) a["setAt"] = 0; + bodies.push_back(body.dump()); + } + // Pinned byte for byte: the publish body has no new fields or events. + REQUIRE(bodies[0] == + R"({"attributes":[{"name":"attr","setAt":0,"value":"value"}],)" + R"("exposures":[{"assigned":true,"audienceMismatch":false,"custom":false,"eligible":true,)" + R"("exposedAt":0,"fullOn":false,"id":1,"name":"exp_plain","overridden":false,)" + R"("ruleOverride":false,"unit":"session_id","variant":1}],)" + R"("goals":[{"achievedAt":0,"name":"goal","properties":{"amount":1}}],"hashed":true,)" + R"("publishedAt":0,"units":[{"type":"session_id","uid":")" + hash_unit(UID) + R"("}]})"); + REQUIRE(bodies[1] == bodies[0]); + REQUIRE(bodies[2] == bodies[0]); +} + +TEST_CASE("Holdouts: model fields are appended last and default-constructed", "[holdouts][compat]") { + // Positional aggregate initialisation written against the released models still compiles + // and leaves the new fields empty. + ExperimentData experiment{1, "exp", "session_id", 1, 0, 0, {0.5, 0.5}}; + REQUIRE(experiment.holdoutIds.empty()); + REQUIRE(experiment.holdoutType.empty()); + ContextData data{{experiment}}; + REQUIRE(data.holdouts.empty()); + HoldoutData holdout; + REQUIRE(holdout.id == 0); + REQUIRE(holdout.split.empty()); +} + +TEST_CASE("Holdouts H1: a refresh that only drops a duplicate holdout id keeps the cached assignment", + "[holdouts][conformance][refresh]") { + // Duplicates collapse at install, so [11, 11] and [11] are the same coverage. + Context context(config_with(UID_NOT_HELD_OUT), + data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_duplicate_ids"), {11, 11})})); + + REQUIRE(context.treatment("exp_duplicate_ids") == 0); + REQUIRE(context.pending() == 2); + + context.refresh(data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_duplicate_ids"), {11})})); + + REQUIRE(context.treatment("exp_duplicate_ids") == 0); + REQUIRE(context.pending() == 2); +} + +TEST_CASE("Holdouts: a variable read with no winner still logs the visited candidate's holdout", + "[holdouts][variables][logger]") { + // Not held out, but outside a strict audience: the unit is in no candidate, so the default + // is returned and only the holdout, which was evaluated, is published and logged (java-sdk). + auto experiment = with_variables(covered_by(new_experiment(1, "exp_strict_mismatch"), {11}), "color"); + experiment.audience = AGE_AUDIENCE; + experiment.audienceStrict = true; + auto logger = std::make_shared(); + Context context(config_with(UID_NOT_HELD_OUT), + data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, {experiment}), logger); + context.set_attribute("age", 5); + + REQUIRE(context.peek_variable_value("color", "default") == "default"); + REQUIRE(context.pending() == 0); + REQUIRE(context.variable_value("color", "default") == "default"); + REQUIRE(logger->exposures.size() == 1); + REQUIRE(logger->exposures[0]["id"] == 11); + require_published(context, {holdout_exposure(11, "holdout_a", 1)}, {{UNIT_TYPE, UID_NOT_HELD_OUT}}); +} + +TEST_CASE("Holdouts: the first suppressed candidate decides a variable's fallback", "[holdouts][variables]") { + // javascript-sdk keeps the first suppressed candidate even if its control lacks the key. + auto first = with_variables(covered_by(new_experiment(1, "exp_first"), {11}), "color"); + first.variants[0].config = R"({"color":"first_control"})"; + auto second = with_variables(covered_by(new_experiment(2, "exp_second"), {11}), "color"); + second.variants[0].config = R"({"color":"second_control"})"; + const auto holdout = new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO); + + Context context(config_with(UID), data_of({holdout}, {first, second})); + REQUIRE(context.peek_variable_value("color", "default") == "first_control"); + REQUIRE(context.variable_value("color", "default") == "first_control"); + + auto keyless = first; + keyless.variants[0].config = R"({"other":1})"; + Context keyless_first(config_with(UID), data_of({holdout}, {keyless, second})); + REQUIRE(keyless_first.peek_variable_value("color", "default") == "default"); + REQUIRE(keyless_first.variable_value("color", "default") == "default"); +} + +// --- Cost --------------------------------------------------------------------------------------- + +namespace { + +template +long allocations_of(F&& f) { + const long before = g_allocations.load(); + f(); + return g_allocations.load() - before; +} + +} // namespace + +TEST_CASE("Holdouts: cached reads of a held-out assignment with a custom assignment allocate nothing", + "[holdouts][cache][cost]") { + // A custom assignment never applies to a held-out unit, so it is not staleness: the cached + // assignment is reused rather than rebuilt on every read. + auto config = config_with(UID); + config.custom_assignments["exp_holdout_custom_cache"] = 3; + Context context(config, data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_holdout_custom_cache"), {11})})); + const std::string name = "exp_holdout_custom_cache"; + + REQUIRE(context.treatment(name) == 0); + REQUIRE(allocations_of([&] { + for (int i = 0; i < 10; ++i) { + context.treatment(name); + context.peek(name); + } + }) == 0); +} + +TEST_CASE("Holdouts: an uncovered experiment resolves without holdout bookkeeping", "[holdouts][cost]") { + // Measured against an experiment missing from the payload, which builds an empty assignment. + // An uncovered experiment adds 2 allocations on main (1.0.0) and here, in a payload with no + // holdouts and in one whose holdouts cover other experiments. + const auto extra_cost = [](const ContextData& data) { + Context context(config_with(UID), data); + context.peek("warm_up"); // hashes the unit and creates its assigner + const std::string plain = "exp_plain"; + const std::string missing = "exp_missing"; + return allocations_of([&] { context.peek(plain); }) - allocations_of([&] { context.peek(missing); }); + }; + const auto plain = new_experiment(1, "exp_plain"); + const auto warm_up = new_experiment(2, "warm_up"); + const auto holdout = new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO); + + REQUIRE(extra_cost(data_of({}, {plain, warm_up})) == 2); + REQUIRE(extra_cost(data_of({holdout}, {plain, covered_by(warm_up, {11})})) == 2); + // Covering it adds its holdout pins. + REQUIRE(extra_cost(data_of({holdout}, {covered_by(plain, {11}), warm_up})) > 2); +} + +TEST_CASE("Holdouts: an uncovered variable read exposes without an event batch, as in 1.0.1", + "[holdouts][cost][variables]") { + // The first exposing variable read of an uncovered experiment costs what its first treatment() + // costs, on top of a cached read of the same value. + struct CountingLogger : ContextEventLogger { + void handle_event(Context&, const std::string&, const json&) override {} + }; + Context context(config_with(UID), + data_of({}, {with_variables(new_experiment(1, "exp_a"), "key_a"), + with_variables(new_experiment(2, "exp_b"), "key_b"), new_experiment(3, "warm_up")}), + std::make_shared()); + context.treatment("warm_up"); // hashes the unit and creates its assigner + const std::string key = "key_a"; + const std::string name = "exp_b"; + const json fallback = "default"; + const long first_read = allocations_of([&] { context.variable_value(key, fallback); }); + const long cached_read = allocations_of([&] { context.variable_value(key, fallback); }); + const long first_treatment = allocations_of([&] { context.treatment(name); }); + REQUIRE(context.pending() == 3); + REQUIRE(first_read - cached_read == first_treatment); +} + +TEST_CASE("Holdouts: an out-of-range or non-integral iteration keeps its default; seeds read as JS ToInt32", + "[holdouts][json]") { + const auto holdout = json::parse(R"({"id": 11, "iteration": 1e20, "seedHi": 1e20, "seedLo": 4294967297, + "split": [0.1, 0.9]})").get(); + REQUIRE(holdout.iteration == 0); + // javascript-sdk: (1e20 | 0) === 1661992960 and (4294967297 | 0) === 1. + REQUIRE(holdout.seedHi == 1661992960); + REQUIRE(holdout.seedLo == 1); + + const auto fractional = json::parse(R"({"id": 11, "seedHi": 1.5, "seedLo": -1.5})").get(); + REQUIRE(fractional.seedHi == 1); + REQUIRE(fractional.seedLo == -1); + + // Negative values wrap rather than clamp: (-4294967297 | 0) === -1, (-2147483649 | 0) === 2147483647. + const auto negative = json::parse(R"({"id": 11, "seedHi": -4294967297, "seedLo": -2147483649})").get(); + REQUIRE(negative.seedHi == -1); + REQUIRE(negative.seedLo == 2147483647); + + // Beyond 2^53 JS holds the integer as a rounded double first: + // (9007199254740995 | 0) === 4 and (18446744073709551615 | 0) === 0. + // Below -2^53 too: (-9007199254740995 | 0) === -4. + REQUIRE(json::parse(R"({"id": 11, "seedHi": -9007199254740995})").get().seedHi == -4); + + const auto huge = json::parse(R"({"id": 11, "seedHi": 9007199254740995, "seedLo": 18446744073709551615})") + .get(); + REQUIRE(huge.seedHi == 4); + REQUIRE(huge.seedLo == 0); + + const auto wrapped = json::parse(R"({"id": 11, "seedHi": 4294967295, "seedLo": -1.0, "iteration": 2.5})") + .get(); + REQUIRE(wrapped.seedHi == -1); + REQUIRE(wrapped.seedLo == -1); + REQUIRE(wrapped.iteration == 0); +} + +TEST_CASE("Holdout arms: only a 3-arm split gives arm 1 its full-on-only meaning", "[holdouts][arms]") { + // javascript-sdk, java-sdk and the collector compare the arm count to 3 exactly: in a 4-arm + // holdout arm 1 holds nothing out. + auto holdout = new_holdout(21, "holdout_four_arm", 0, 1); + holdout.split = {0.25, 0.25, 0.25, 0.25}; + Context context(config_with(UID), data_of({holdout}, {covered_by(new_experiment(1, "exp_four_arm"), {21})})); + + REQUIRE(context.treatment("exp_four_arm") == NORMAL_VARIANT); + require_published(context, {own_exposure(1, "exp_four_arm", NORMAL_VARIANT), holdout_exposure(21, "holdout_four_arm", 1)}); +} + +// --- Review follow-ups ---------------------------------------------------------------------------- + +TEST_CASE("Holdouts: a logger that refreshes on every exposure does not change the variable_value result", + "[holdouts][variables][refresh]") { + // The first candidate is assigned to variant 0, which lacks the key: it wins with the default + // (1.0.1), and the logger's refresh runs only after the read is decided. + auto first = with_variables(new_experiment(1, "exp_first"), "color"); + first.split = {1.0, 0.0}; + first.variants = {{"A", R"({"other":1})"}, {"B", R"({"color":"first"})"}}; + auto second = with_variables(new_experiment(2, "exp_second"), "color"); + const auto data = data_of({}, {first, second}); + + int refreshes = 0; + auto logger = std::make_shared(); + logger->on_exposure = [&](Context& context, const json&) { + ++refreshes; + context.refresh(data); + }; + Context context(config_with(UID), data, logger); + + REQUIRE(context.variable_value("color", "default") == "default"); + REQUIRE(context.pending() == 1); + REQUIRE(refreshes == 1); + REQUIRE(context.variable_value("color", "default") == "default"); + REQUIRE(context.pending() == 1); + REQUIRE(logger->exposures.at(0)["name"] == "exp_first"); +} + +TEST_CASE("Holdouts: a logger that refreshes during variable_value does not invalidate the walk", + "[holdouts][variables][refresh]") { + // The first candidate is suppressed; its holdout exposure's logger refreshes with data that + // drops the variable from it, replacing the index variable_value is walking. + auto suppressed = with_variables(covered_by(new_experiment(1, "exp_first_suppressed"), {11}), "color"); + auto assigned = with_variables(new_experiment(2, "exp_second_assigned"), "color"); + const auto holdout = new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO); + auto without_first = suppressed; + without_first.variants = {{"A", nullptr}, {"B", nullptr}}; + const auto refreshed = data_of({holdout}, {without_first, assigned}); + + auto logger = std::make_shared(); + logger->on_exposure = [&](Context& context, const json& data) { + if (data["id"] == 11) context.refresh(refreshed); + }; + Context context(config_with(UID), data_of({holdout}, {suppressed, assigned}), logger); + + REQUIRE(context.variable_value("color", "default") == "treatment"); + require_published(context, {holdout_exposure(11, "holdout_a", 0), + own_exposure(2, "exp_second_assigned", NORMAL_VARIANT)}); +} + +TEST_CASE("Holdouts: an uncovered override is kept across a unit type change, as in JS", "[holdouts][refresh]") { + ContextConfig config; + config.units = {{UNIT_TYPE, UID}, {"user_id", UID_NOT_HELD_OUT}}; + config.overrides["exp_override_plain"] = 1; + Context context(config, data_of({}, {new_experiment(1, "exp_override_plain")})); + + REQUIRE(context.treatment("exp_override_plain") == 1); + context.refresh(data_of({}, {new_experiment(1, "exp_override_plain", "user_id", 0)})); + REQUIRE(context.treatment("exp_override_plain") == 1); + REQUIRE(context.pending() == 1); +} + +TEST_CASE("Holdouts: a covered override is kept across a unit type change, as in JS", "[holdouts][refresh]") { + // javascript-sdk and java-sdk revalidate an override by its variant and holdout set only. + ContextConfig config; + config.units = {{UNIT_TYPE, UID}, {"user_id", UID_NOT_HELD_OUT}}; + config.overrides["exp_override_unit_type"] = 1; + const auto holdout = new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO); + Context context(config, data_of({holdout}, {covered_by(new_experiment(1, "exp_override_unit_type"), {11})})); + + REQUIRE(context.treatment("exp_override_unit_type") == 1); + REQUIRE(context.pending() == 2); + + context.refresh(data_of({holdout}, {covered_by(new_experiment(1, "exp_override_unit_type", "user_id", 0), {11})})); + REQUIRE(context.treatment("exp_override_unit_type") == 1); + REQUIRE(context.pending() == 2); +} + +TEST_CASE("Holdouts: decoding into reused models replaces holdouts and holdoutIds", "[holdouts][json]") { + ContextData data; + json::parse(R"({"experiments":[],"holdouts":[{"id":11,"split":[0.1,0.9]}]})").get_to(data); + REQUIRE(data.holdouts.size() == 1); + json::parse(R"({"experiments":[],"holdouts":[]})").get_to(data); + REQUIRE(data.holdouts.empty()); + json::parse(R"({"experiments":[],"holdouts":[{"id":11,"split":[0.1,0.9]}]})").get_to(data); + json::parse(R"({"experiments":[]})").get_to(data); + REQUIRE(data.holdouts.empty()); + + ExperimentData experiment; + const auto with_ids = json::parse(R"({"id":1,"name":"e","unitType":"u","iteration":1,"seedHi":0,"seedLo":0, + "holdoutIds":[11]})"); + auto without_ids = with_ids; + without_ids["holdoutIds"] = json::array(); + with_ids.get_to(experiment); + REQUIRE(experiment.holdoutIds == std::vector{11}); + without_ids.get_to(experiment); + REQUIRE(experiment.holdoutIds.empty()); + + // Omitted, null or not an array: also no coverage, as with ContextData::holdouts. + for (const char* ids : {"absent", "null", "\"11\""}) { + auto payload = with_ids; + payload["holdoutType"] = "full"; + payload.get_to(experiment); + REQUIRE(experiment.holdoutIds == std::vector{11}); + REQUIRE(experiment.holdoutType == "full"); + auto next = with_ids; + if (std::string(ids) == "absent") next.erase("holdoutIds"); else next["holdoutIds"] = json::parse(ids); + next.get_to(experiment); + REQUIRE(experiment.holdoutIds.empty()); + REQUIRE(experiment.holdoutType.empty()); + } +} + +TEST_CASE("Holdouts: integer and float spellings of a large seed read the same", "[holdouts][json]") { + // (9007199254740993 | 0) === 0 in JS: the integer rounds to 9007199254740992 first. + const auto integer = json::parse(R"({"id": 11, "seedHi": 9007199254740993})").get(); + const auto floating = json::parse(R"({"id": 11, "seedHi": 9007199254740993.0})").get(); + REQUIRE(integer.seedHi == 0); + REQUIRE(floating.seedHi == 0); +} + +TEST_CASE("Holdouts: cached variable reads do not capture candidate names", "[holdouts][cost]") { + // The first candidate's unit is missing, so every read checks it and goes on to the second. + auto first = new_experiment(1, "first_experiment_with_a_long_name", "user_id"); + first.variants = {{"A", R"({"other":1})"}, {"B", R"({"number":1})"}}; + auto second = new_experiment(2, "second_experiment_with_a_long_name"); + second.variants = {{"A", R"({"number":0})"}, {"B", R"({"number":42})"}}; + Context context(config_with(UID), data_of({}, {first, second})); + const std::string key = "number"; + const json fallback = 0; + REQUIRE(context.variable_value(key, fallback) == 42); + REQUIRE(allocations_of([&] { + for (int i = 0; i < 10; ++i) context.variable_value(key, fallback); + }) == 0); +} + +// --- A logger that finalizes from an exposure --------------------------------------------------- + +namespace { + +struct FinalizingLogger : ContextEventLogger { + bool finalized = false; + std::vector flushed; + std::vector events; + void handle_event(Context& context, const std::string& type, const json& data) override { + events.push_back(type == "exposure" ? "exposure:" + data["name"].get() : type); + if (type == "exposure" && !finalized) { + finalized = true; + flushed.push_back(context.finalize()); + } + } +}; + +} // namespace + +TEST_CASE("Holdouts: a logger that finalizes on the first exposure still flushes the holdout exposures", + "[holdouts][logger][finalize]") { + // treatment() queues the experiment's own exposure and its holdouts' exposures before any + // callback runs, so finalize() from the first callback publishes all of them. + auto logger = std::make_shared(); + Context context(config_with(UID_NOT_HELD_OUT), + data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO), + new_holdout(12, "holdout_b", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {covered_by(new_experiment(1, "exp_finalize"), {11, 12})}), + logger); + + REQUIRE(context.treatment("exp_finalize") == 0); + REQUIRE(context.is_finalized()); + REQUIRE(context.pending() == 0); + REQUIRE(logger->flushed.size() == 1); + std::vector names; + for (const auto& exposure : logger->flushed[0].exposures) names.push_back(exposure.name); + REQUIRE(names == std::vector{"exp_finalize", "holdout_a", "holdout_b"}); +} + +TEST_CASE("Holdouts: a held-out unit's holdout exposures all flush when a logger finalizes", + "[holdouts][logger][finalize]") { + // Suppressed: no own exposure, so the first callback is the first holdout's. + auto logger = std::make_shared(); + Context context(config_with(UID), + data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO), + new_holdout(12, "holdout_b", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {covered_by(new_experiment(1, "exp_finalize"), {11, 12})}), + logger); + + REQUIRE(context.treatment("exp_finalize") == 0); + REQUIRE(context.pending() == 0); + REQUIRE(logger->flushed.at(0).exposures.size() == 2); +} + +TEST_CASE("Holdouts: a logger that finalizes from a variable_value exposure flushes the whole read", + "[holdouts][logger][finalize][variables]") { + // The held-out first candidate's holdout, the second candidate's holdout and the winner's own + // exposure are all queued before the first callback, as in javascript-sdk 1.14. + auto logger = std::make_shared(); + Context context(config_with(UID), + data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO), + new_holdout(12, "holdout_b", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {with_variables(covered_by(new_experiment(1, "exp_first_held_out"), {11}), "color"), + with_variables(covered_by(new_experiment(2, "exp_second"), {12}), "color")}), + logger); + + REQUIRE(context.variable_value("color", "default") == "treatment"); + REQUIRE(context.is_finalized()); + REQUIRE(context.pending() == 0); + std::vector names; + for (const auto& exposure : logger->flushed.at(0).exposures) names.push_back(exposure.name); + REQUIRE(names == std::vector{"holdout_a", "holdout_b", "exp_second"}); +} + +TEST_CASE("Holdouts: a covered call logs its own exposure, then its holdouts in id order", "[holdouts][logger]") { + // All exposures are queued first, then delivered to the logger in queue order. + auto logger = std::make_shared(); + Context context(config_with(UID_NOT_HELD_OUT), + data_of({new_holdout(12, "holdout_b", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO), + new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {covered_by(new_experiment(1, "exp_order"), {12, 11})}), + logger); + + std::vector pending_at_callback; + logger->on_exposure = [&](Context& c, const json&) { pending_at_callback.push_back(static_cast(c.pending())); }; + context.treatment("exp_order"); + + std::vector names; + for (const auto& exposure : logger->exposures) names.push_back(exposure["name"]); + REQUIRE(names == std::vector{"exp_order", "holdout_a", "holdout_b"}); + REQUIRE(pending_at_callback == std::vector{3, 3, 3}); +} + +// Measured with this exact fixture and logger against main (1.0.0): 69, with GCC 15.2 and its +// libstdc++ 15 (CI's ubuntu-26.04 image) and the pinned nlohmann/json. The count includes the +// standard library's and nlohmann/json's allocations, so it is asserted for exactly that compiler +// and library; elsewhere only the exposures are checked. +constexpr long UNCOVERED_FIRST_TREATMENT_ALLOCATIONS = 69; + +TEST_CASE("Holdouts: an uncovered first exposure allocates as on 1.0.0", "[holdouts][cost]") { + // Measured against main (1.0.0) with the same logger: the first treatment() of an + // uncovered experiment costs the same, so the uncovered path takes no batch. + struct CountingLogger : ContextEventLogger { + int exposures = 0; + void handle_event(Context&, const std::string& type, const json&) override { + if (type == "exposure") ++exposures; + } + }; + auto logger = std::make_shared(); + Context context(config_with(UID), data_of({}, {new_experiment(1, "exp_plain"), new_experiment(2, "warm_up")}), + logger); + context.treatment("warm_up"); // hashes the unit and creates its assigner + const std::string name = "exp_plain"; + const long allocations = allocations_of([&] { context.treatment(name); }); + REQUIRE(logger->exposures == 2); +#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ == 15 && __GNUC_MINOR__ == 2 && \ + defined(_GLIBCXX_RELEASE) && _GLIBCXX_RELEASE == 15 + REQUIRE(allocations == UNCOVERED_FIRST_TREATMENT_ALLOCATIONS); +#else + REQUIRE(allocations > 0); +#endif +} + +TEST_CASE("Holdouts: treatment returns its decision when the logger refreshes and re-resolves it", + "[holdouts][logger][refresh]") { + // The held-out decision is control. The holdout's logger refreshes to an iteration that is no + // longer covered and peeks the experiment, replacing the cached assignment with variant 1. + // As in JS, the outer call still returns the decision it exposed. + const auto holdout = new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO); + auto next = new_experiment(1, "exp_reentrant"); + next.iteration = 2; + const auto refreshed = data_of({holdout}, {next}); + int peeked = -1; + auto logger = std::make_shared(); + logger->on_exposure = [&](Context& context, const json&) { + if (peeked < 0) { + context.refresh(refreshed); + peeked = context.peek("exp_reentrant"); + } + }; + Context context(config_with(UID), data_of({holdout}, {covered_by(new_experiment(1, "exp_reentrant"), {11})}), + logger); + + REQUIRE(context.treatment("exp_reentrant") == 0); + REQUIRE(peeked == NORMAL_VARIANT); + require_published(context, {holdout_exposure(11, "holdout_a", 0)}); +} + +TEST_CASE("Holdouts: variable_value returns its decision when the logger refreshes and re-resolves it", + "[holdouts][logger][refresh][variables]") { + const auto holdout = new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO); + auto next = with_variables(new_experiment(1, "exp_reentrant"), "color"); + next.iteration = 2; + const auto refreshed = data_of({holdout}, {next}); + json peeked; + auto logger = std::make_shared(); + logger->on_exposure = [&](Context& context, const json&) { + if (peeked.is_null()) { + context.refresh(refreshed); + peeked = context.peek_variable_value("color", "default"); + } + }; + Context context(config_with(UID), + data_of({holdout}, {with_variables(covered_by(new_experiment(1, "exp_reentrant"), {11}), "color")}), + logger); + + REQUIRE(context.variable_value("color", "default") == "control"); + REQUIRE(peeked == "treatment"); + require_published(context, {holdout_exposure(11, "holdout_a", 0)}); +} + +TEST_CASE("Holdouts: an assigned variable winner is returned even if the logger re-resolves it", + "[holdouts][logger][refresh][variables]") { + // Not held out: the experiment wins "treatment". Its logger refreshes into coverage that + // holds the unit out, so the cached assignment becomes suppressed control. + const auto holdout = new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO); + auto next = with_variables(covered_by(new_experiment(1, "exp_reentrant"), {11}), "color"); + const auto refreshed = data_of({holdout}, {next}); + json peeked; + auto logger = std::make_shared(); + logger->on_exposure = [&](Context& context, const json&) { + if (peeked.is_null()) { + context.refresh(refreshed); + peeked = context.peek_variable_value("color", "default"); + } + }; + Context context(config_with(UID), data_of({holdout}, {with_variables(new_experiment(1, "exp_reentrant"), "color")}), + logger); + + REQUIRE(context.variable_value("color", "default") == "treatment"); + REQUIRE(peeked == "control"); +} + +namespace { + +ContextData shared_key_data(int count) { + std::vector experiments; + for (int i = 0; i < count; ++i) { + auto experiment = new_experiment(100 + i, "experiment_with_a_long_enough_name_to_allocate_" + std::to_string(i)); + experiment.split = {1.0, 0.0}; + experiment.variants = {{"A", R"({"number":7})"}, {"B", R"({"number":8})"}}; + experiments.push_back(experiment); + } + experiments.push_back(new_experiment(1, "warm_up")); + return data_of({}, experiments); +} + +} // namespace + +TEST_CASE("Holdouts: a first variable read does not cost per remaining candidate", "[holdouts][cost][variables]") { + // The first candidate wins, so the other candidates are never looked at; the cost must not + // grow with how many there are, with or without a logger. + const auto first_read = [](int count, bool with_logger) { + std::shared_ptr logger; + if (with_logger) logger = std::make_shared(); + Context context(config_with(UID), shared_key_data(count), logger); + context.treatment("warm_up"); // hashes the unit and creates its assigner + const std::string key = "number"; + const json fallback = 0; + json result; + const long cost = allocations_of([&] { result = context.variable_value(key, fallback); }); + REQUIRE(result == 7); + return cost; + }; + REQUIRE(first_read(1000, false) == first_read(2, false)); + REQUIRE(first_read(1000, true) == first_read(2, true)); +} + +TEST_CASE("Holdouts: cached reads of a suppressed assignment skip its audience", "[holdouts][cost][cache]") { + auto experiment = covered_by(new_experiment(1, "exp_suppressed_audience"), {11}); + experiment.audience = R"({"filter":[{"gte":[{"var":"age"},{"value":20}]},{"eq":[{"var":"tier"},{"value":"a long tier name"}]}]})"; + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {experiment})); + const std::string name = "exp_suppressed_audience"; + + REQUIRE(context.peek(name) == 0); + REQUIRE(allocations_of([&] { + for (int i = 0; i < 100; ++i) context.peek(name); + }) == 0); + context.set_attribute("unrelated", 1); + REQUIRE(allocations_of([&] { context.peek(name); }) == 0); + REQUIRE(allocations_of([&] { context.peek(name); }) == 0); + REQUIRE(context.treatment(name) == 0); + require_published(context, {holdout_exposure(11, "holdout_a", 0)}); +} + +TEST_CASE("Holdouts: a suppressed assignment with an audience still re-resolves when a rule starts matching", + "[holdouts][cache][rules]") { + auto experiment = covered_by(new_experiment(1, "exp_suppressed_rule"), {11}); + experiment.audience = AGE_AUDIENCE; + experiment.assignmentRules = US_RULE; + Context context(config_with(UID), data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {experiment})); + context.set_attribute("country", "GB"); + REQUIRE(context.peek("exp_suppressed_rule") == 0); + context.set_attribute("country", "US"); + REQUIRE(context.peek("exp_suppressed_rule") == 1); +} + +TEST_CASE("Holdouts: removing coverage restores the normal assignment with a fresh exposure (scenario 225)", + "[holdouts][refresh]") { + const auto holdout = new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO); + const auto plain = new_experiment(1, "exp_coverage_change"); + Context context(config_with(UID), data_of({holdout}, {plain})); + + REQUIRE(context.treatment("exp_coverage_change") == NORMAL_VARIANT); + context.refresh(data_of({holdout}, {covered_by(plain, {11})})); + REQUIRE(context.treatment("exp_coverage_change") == 0); + context.refresh(data_of({holdout}, {plain})); + REQUIRE(context.treatment("exp_coverage_change") == NORMAL_VARIANT); + require_published(context, {own_exposure(1, "exp_coverage_change", NORMAL_VARIANT), + holdout_exposure(11, "holdout_a", 0), + own_exposure(1, "exp_coverage_change", NORMAL_VARIANT)}); +} + +TEST_CASE("Holdouts: a refresh that adds a holdout to the coverage re-resolves the assignment", + "[holdouts][refresh]") { + // javascript-sdk holdoutSetMatches: a grown holdout set is a new decision. Holdout 12 holds + // the unit out, so the experiment turns control and only the new holdout is exposed. + const auto not_holding_out = new_holdout(11, "holdout_b", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO); + const auto holding_out = new_holdout(12, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO); + const auto experiment = new_experiment(1, "exp_coverage_grows"); + Context context(config_with(UID), data_of({not_holding_out, holding_out}, {covered_by(experiment, {11})})); + + REQUIRE(context.treatment("exp_coverage_grows") == NORMAL_VARIANT); + context.refresh(data_of({not_holding_out, holding_out}, {covered_by(experiment, {11, 12})})); + REQUIRE(context.treatment("exp_coverage_grows") == 0); + REQUIRE(context.treatment("exp_coverage_grows") == 0); + require_published(context, {own_exposure(1, "exp_coverage_grows", NORMAL_VARIANT), + holdout_exposure(11, "holdout_b", 1), holdout_exposure(12, "holdout_a", 0)}); +} + +TEST_CASE("Holdouts: a refresh that swaps the covering holdout re-resolves the assignment", + "[holdouts][refresh]") { + // Same count and iteration, different id: a new coverage, so the unit is re-decided against + // holdout 12, which holds it out, and only holdout 12 is newly exposed. + const auto not_holding_out = new_holdout(11, "holdout_b", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO); + const auto holding_out = new_holdout(12, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO); + const auto experiment = new_experiment(1, "exp_coverage_swaps"); + Context context(config_with(UID), data_of({not_holding_out, holding_out}, {covered_by(experiment, {11})})); + + REQUIRE(context.treatment("exp_coverage_swaps") == NORMAL_VARIANT); + context.refresh(data_of({not_holding_out, holding_out}, {covered_by(experiment, {12})})); + REQUIRE(context.peek("exp_coverage_swaps") == 0); + REQUIRE(context.treatment("exp_coverage_swaps") == 0); + require_published(context, {own_exposure(1, "exp_coverage_swaps", NORMAL_VARIANT), + holdout_exposure(11, "holdout_b", 1), holdout_exposure(12, "holdout_a", 0)}); +} + +TEST_CASE("Holdouts: a held-out variable winner whose holdout is already exposed publishes nothing", + "[holdouts][variables]") { + // treatment() of A exposes holdout 11. B, held out by the same holdout, then wins its key as + // the fallback with no new holdout exposure; it must still publish no exposure of its own. + const auto holdout = new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO); + auto logger = std::make_shared(); + Context context(config_with(UID), + data_of({holdout}, {covered_by(new_experiment(1, "exp_a"), {11}), + with_variables(covered_by(new_experiment(2, "exp_b"), {11}), "color")}), + logger); + + REQUIRE(context.treatment("exp_a") == 0); + REQUIRE(context.variable_value("color", "default") == "control"); + REQUIRE(logger->exposures.size() == 1); + require_published(context, {holdout_exposure(11, "holdout_a", 0)}); +} + +TEST_CASE("Holdouts: a logger that refreshes with the context's own data during variable_value keeps it", + "[holdouts][logger][refresh][variables]") { + auto first = with_variables(new_experiment(1, "exp_first"), "color"); + first.split = {1.0, 0.0}; + first.variants = {{"A", R"({"other":1})"}, {"B", R"({"color":"first"})"}}; + auto logger = std::make_shared(); + bool refreshed = false; + logger->on_exposure = [&](Context& context, const json&) { + if (!refreshed) { + refreshed = true; + context.refresh(context.data()); + } + }; + Context context(config_with(UID), data_of({}, {first, with_variables(new_experiment(2, "exp_second"), "color")}), + logger); + + REQUIRE(context.variable_value("color", "default") == "default"); + REQUIRE(refreshed); + REQUIRE(context.data().experiments.size() == 2); + REQUIRE(context.treatment("exp_second") == NORMAL_VARIANT); +} + +TEST_CASE("Holdouts: an overridden candidate wins over a held-out fallback even without the key", "[holdouts][variables]") { + // java-sdk getVariableAssignment: an override wins the key; its variant lacks it, so the + // caller default is returned, never the later held-out candidate's control value. + auto overridden = covered_by(new_experiment(1, "exp_overridden"), {11}); + overridden.variants = {{"A", R"({"color":"override-control"})"}, {"B", R"({"other":1})"}}; + auto held_out = with_variables(covered_by(new_experiment(2, "exp_held_out"), {11}), "color"); + auto config = config_with(UID); + config.overrides["exp_overridden"] = 1; + const auto data = data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, {overridden, held_out}); + + Context peeking(config, data); + REQUIRE(peeking.peek_variable_value("color", "default") == "default"); + Context context(config, data); + REQUIRE(context.variable_value("color", "default") == "default"); + Expected own = own_exposure(1, "exp_overridden", 1); + own.assigned = false; + own.overridden = true; + require_published(context, {holdout_exposure(11, "holdout_a", 0), own}); +} + +TEST_CASE("Holdouts: a rule-won candidate wins over a held-out fallback even without the key", + "[holdouts][variables][rules]") { + // The first candidate is held out but a rule wins it a variant without the key; as in + // java-sdk the rule win takes the key, so the caller default is returned. + auto rule_won = covered_by(new_experiment(1, "exp_rule_won"), {11}); + rule_won.assignmentRules = US_RULE; + rule_won.variants = {{"A", R"({"color":"rule-control"})"}, {"B", R"({"other":1})"}}; + auto held_out = with_variables(covered_by(new_experiment(2, "exp_held_out"), {11}), "color"); + const auto data = data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, {rule_won, held_out}); + + Context peeking(config_with(UID), data); + peeking.set_attribute("country", "US"); + REQUIRE(peeking.peek_variable_value("color", "default") == "default"); + Context context(config_with(UID), data); + context.set_attribute("country", "US"); + REQUIRE(context.variable_value("color", "default") == "default"); + Expected own = own_exposure(1, "exp_rule_won", 1); + own.assigned = false; + own.rule_override = true; + require_published(context, {holdout_exposure(11, "holdout_a", 0), own}); +} + +TEST_CASE("Holdouts: a logger that refreshes with data() from a variable_value exposure is safe", "[holdouts][refresh][cache]") { + auto log = std::make_shared(); + int refreshes = 0; + log->on_exposure = [&](Context& c, const json&) { if (refreshes++ < 3) c.refresh(c.data()); }; + Context context(config_with(UID), + data_of({}, {with_variables(new_experiment(1, "exp_a"), "color"), + with_variables(new_experiment(2, "exp_b"), "color")}), + log); + REQUIRE(context.variable_value("color", "d") == "treatment"); + REQUIRE(refreshes >= 1); +} + +TEST_CASE("Holdouts: set_unit of another unit type keeps a peeked assignment with an unresolved holdout", "[holdouts][refresh][cache]") { + auto data = data_of({new_holdout(11, "holdout_user_id", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO, "user_id")}, + {covered_by(with_variables(new_experiment(1, "exp_user", "user_id", 1), "color"), {11})}); + Context context(ContextConfig{}, data); + REQUIRE(context.peek_variable_value("color", "d") == "treatment"); + auto edited = data; + edited.experiments[0].variants[1].config = json({{"color", "edited"}}).dump(); + context.refresh(edited); + // Same iteration: the peeked assignment stays cached, as in javascript-sdk. + REQUIRE(context.peek_variable_value("color", "d") == "treatment"); + context.set_unit("session_id", UID); + REQUIRE(context.peek_variable_value("color", "d") == "treatment"); + context.set_unit("user_id", UID); + REQUIRE(context.peek_variable_value("color", "d") == "edited"); +} + +TEST_CASE("Holdouts: a variable read from a refreshing exposure logger reads the refreshed data", + "[holdouts][logger][refresh][variables]") { + // The outer read is decided and queued before its logger runs; the logger refreshes and + // makes a nested read against the new data. + const auto data = data_of({}, {with_variables(new_experiment(1, "exp_color"), "color"), + with_variables(new_experiment(2, "exp_shape"), "shape")}); + auto refreshed = data; + refreshed.experiments[1].variants[1].config = R"({"shape":"square"})"; + json inner; + auto logger = std::make_shared(); + logger->on_exposure = [&](Context& context, const json& event) { + if (event["name"] == "exp_color") { + context.refresh(refreshed); + inner = context.variable_value("shape", "none"); + } + }; + Context context(config_with(UID), data, logger); + + REQUIRE(context.variable_value("color", "default") == "treatment"); + REQUIRE(inner == "square"); + REQUIRE(context.pending() == 2); +} + +TEST_CASE("Holdouts: a refresh from a variant parse error during a walk leaves a valid index", + "[holdouts][logger][refresh][variables]") { + // The exposure refreshes to data with a malformed variant config; the error logger + // refreshes again. The parse error is reported after its index is complete. + const auto good = data_of({}, {with_variables(new_experiment(1, "exp_first"), "color"), + with_variables(new_experiment(2, "exp_second"), "color")}); + auto bad = good; + bad.experiments[0].variants[1].config = "{not json"; + struct Logger : ContextEventLogger { + const ContextData* good = nullptr; + const ContextData* bad = nullptr; + int errors = 0; + bool refreshed = false; + void handle_event(Context& context, const std::string& type, const json&) override { + if (type == "exposure" && !refreshed) { + refreshed = true; + context.refresh(*bad); + } else if (type == "error") { + ++errors; + context.refresh(*good); + } + } + }; + auto logger = std::make_shared(); + logger->good = &good; + logger->bad = &bad; + Context context(config_with(UID), good, logger); + + REQUIRE(context.variable_value("color", "default") == "treatment"); + REQUIRE(logger->errors == 1); + REQUIRE(context.peek_variable_value("color", "default") == "treatment"); + REQUIRE(context.treatment("exp_first") == NORMAL_VARIANT); +} + +TEST_CASE("Holdouts: a hash on a split boundary picks the arm JS picks", "[holdouts][arms][verdicts]") { + // JS scales the hash by 1/0xffffffff, so a hash whose scaled value equals the first split + // boundary lands in arm 1 (the comparison is strict). Scaling by 1/2^32 lands just below it. + const uint32_t unit_hash = murmur3_32(hash_unit(UID), 0); + uint8_t buffer[12]; + const auto put = [&](int at, uint32_t value) { + for (int i = 0; i < 4; ++i) buffer[at + i] = static_cast(value >> (8 * i)); + }; + put(0, static_cast(HOLDOUT_A_SEED_LO)); + put(4, static_cast(HOLDOUT_A_SEED_HI)); + put(8, unit_hash); + const uint32_t hash = murmur3_32(buffer, 12, 0); + const double boundary = hash * (1.0 / 0xffffffff); + REQUIRE(static_cast(hash) / 4294967296.0 < boundary); + + auto holdout = new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO); + holdout.split = {boundary, 1.0 - boundary}; + Context context(config_with(UID), data_of({holdout}, {covered_by(new_experiment(1, "exp_boundary"), {11})})); + + REQUIRE(context.treatment("exp_boundary") == NORMAL_VARIANT); + require_published(context, {own_exposure(1, "exp_boundary", NORMAL_VARIANT), holdout_exposure(11, "holdout_a", 1)}); +} + +TEST_CASE("Holdouts: exposed variable reads keep returning control", "[holdouts][variables][cache]") { + Context context(config_with(UID), + data_of({new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO)}, + {with_variables(covered_by(new_experiment(1, "exp_held"), {11}), "color")})); + + REQUIRE(context.variable_value("color", "default") == "control"); + REQUIRE(context.variable_value("color", "default") == "control"); + REQUIRE(context.peek_variable_value("color", "default") == "control"); + require_published(context, {holdout_exposure(11, "holdout_a", 0)}); +} + +TEST_CASE("Holdouts: a parse-error logger can replace the payload with an empty one", + "[holdouts][logger][refresh][variables]") { + const auto good = data_of({}, {with_variables(new_experiment(1, "exp_color"), "color"), + with_variables(new_experiment(2, "exp_shape"), "shape")}); + auto bad = good; + bad.experiments[0].variants[0].config = "{not json"; + struct Logger : ContextEventLogger { + int errors = 0; + void handle_event(Context& context, const std::string& type, const json&) override { + if (type == "error") { + ++errors; + context.refresh(ContextData{}); + } + } + }; + auto logger = std::make_shared(); + Context context(config_with(UID), good, logger); + context.refresh(bad); + + REQUIRE(logger->errors == 1); + REQUIRE(context.data().experiments.empty()); + REQUIRE(context.peek_variable_value("color", "default") == "default"); + REQUIRE(context.variable_value("shape", "default") == "default"); +} + +TEST_CASE("Holdouts: variable reads reuse each candidate's index entry", "[holdouts][variables][cost]") { + // The first candidate's unit is missing, so each read checks both candidates. Each check + // must use the indexed entry, not look the experiment up by name again. + auto first = with_variables(new_experiment(1, "exp_first", "user_id"), "color"); + Context context(config_with(UID), data_of({}, {first, with_variables(new_experiment(2, "exp_second"), "color")})); + REQUIRE(context.variable_value("color", "default") == "treatment"); + + const auto before = ContextTestAccess::index_reuses(context); + REQUIRE(context.variable_value("color", "default") == "treatment"); + REQUIRE(context.peek_variable_value("color", "default") == "treatment"); + REQUIRE(ContextTestAccess::index_reuses(context) == before + 4); + context.peek("exp_second"); + REQUIRE(ContextTestAccess::index_reuses(context) == before + 4); +} + +TEST_CASE("Holdouts: ExperimentData keeps its 1.0.0 structured-binding shape", "[holdouts][compat]") { + static_assert(std::tuple_size_v == 19); + static_assert(std::is_same_v, int>); + static_assert(std::is_same_v, int32_t>); + static_assert(std::is_same_v, json>); + static_assert(std::is_same_v, std::string>); + static_assert(std::is_same_v(std::declval())), std::string&>); + static_assert(std::is_same_v(std::declval())), const std::string&>); + static_assert(std::is_same_v(std::declval())), std::string&&>); + static_assert(std::is_same_v(std::declval())), const std::string&&>); + + ExperimentData e; + auto& [id, name, unitType, iteration, seedHi, seedLo, split, seedStrictMode, trafficSeedHi, trafficSeedLo, + trafficSplit, fullOnVariant, audience, variants, audienceStrict, customFieldValues, application, + environment, assignmentRules] = e; + const std::vector bound = {&id, &name, &unitType, &iteration, &seedHi, &seedLo, &split, + &seedStrictMode, &trafficSeedHi, &trafficSeedLo, &trafficSplit, + &fullOnVariant, &audience, &variants, &audienceStrict, + &customFieldValues, &application, &environment, &assignmentRules}; + const std::vector members = {&e.id, &e.name, &e.unitType, &e.iteration, &e.seedHi, &e.seedLo, + &e.split, &e.seedStrictMode, &e.trafficSeedHi, &e.trafficSeedLo, + &e.trafficSplit, &e.fullOnVariant, &e.audience, &e.variants, + &e.audienceStrict, &e.customFieldValues, &e.application, + &e.environment, &e.assignmentRules}; + REQUIRE(bound == members); + + ExperimentData source; + source.name = "moved"; + auto&& [mid, moved_name, mu, mi, msh, msl, ms, mssm, mtsh, mtsl, mts, mfov, ma, mv, mas, mcfv, mapp, menv, mr] = + std::move(source); + std::string taken = std::move(moved_name); + REQUIRE(taken == "moved"); + REQUIRE(source.name.empty()); + + ContextData data; + auto& [experiments] = data; + REQUIRE(&experiments == &data.experiments); +} + +TEST_CASE("Holdouts: a refresh that fails while copying or indexing leaves the installed data usable", + "[holdouts][refresh]") { + // Each allocation of the payload copy, then the first allocations of indexing it, is made to + // fail; whichever one throws, the context keeps serving the data it had, through a valid + // index. (Not further: nlohmann's json destructor allocates while noexcept, so a failure deep + // in indexing terminates. Measured on GCC 15.2: the copy takes 18 allocations, failures up to + // 32 throw cleanly and 33 aborts, so copy + 8 = 26 leaves a margin of 6.) + const auto holdout = new_holdout(11, "holdout_a", HOLDOUT_A_SEED_HI, HOLDOUT_A_SEED_LO); + const auto installed = data_of({holdout}, {with_variables(new_experiment(1, "exp_old"), "color")}); + const auto incoming = data_of({holdout, new_holdout(12, "holdout_b", HOLDOUT_B_SEED_HI, HOLDOUT_B_SEED_LO)}, + {with_variables(new_experiment(2, "exp_new"), "color"), + with_variables(new_experiment(3, "exp_new_2"), "shape")}); + const long copy_allocations = allocations_of([&] { ContextData copy = incoming; }); + REQUIRE(copy_allocations > 4); + + for (long fail_at = 1; fail_at <= copy_allocations + 8; ++fail_at) { + INFO("allocation " << fail_at << " of the refresh failed"); + Context context(config_with(UID_NOT_HELD_OUT), installed); + g_fail_after = fail_at; + REQUIRE_THROWS_AS(context.refresh(incoming), std::bad_alloc); + g_fail_after = 0; + REQUIRE(context.data().experiments.size() == 1); + REQUIRE(context.data().holdouts.size() == 1); + REQUIRE(context.peek("exp_old") == 0); + REQUIRE(context.peek_variable_value("color", "default") == "control"); + } +} diff --git a/tests/json_expr_test.cpp b/tests/json_expr_test.cpp index d2f21ec..4acb14d 100644 --- a/tests/json_expr_test.cpp +++ b/tests/json_expr_test.cpp @@ -398,12 +398,16 @@ TEST_CASE("JsonExpr integration tests", "[evaluator][integration]") { } SECTION("membership is haystack-first and preserves null results") { - auto english = binary_op("in", value_for(json::array({"en-US", "en-GB"})), var_for("language")); - REQUIRE(evaluator.evaluate_boolean(english, john)); - REQUIRE(evaluator.evaluate_boolean(english, terry)); - REQUIRE_FALSE(evaluator.evaluate_boolean(english, kate)); - REQUIRE_FALSE(evaluator.evaluate_boolean(english, maria)); - REQUIRE(evaluator.evaluate(binary_op("in", value_for(nullptr), var_for("language")), john).is_null()); + // `contains` is an alias of `in`. + for (const char* op : {"in", "contains"}) { + CAPTURE(op); + auto english = binary_op(op, value_for(json::array({"en-US", "en-GB"})), var_for("language")); + REQUIRE(evaluator.evaluate_boolean(english, john)); + REQUIRE(evaluator.evaluate_boolean(english, terry)); + REQUIRE_FALSE(evaluator.evaluate_boolean(english, kate)); + REQUIRE_FALSE(evaluator.evaluate_boolean(english, maria)); + REQUIRE(evaluator.evaluate(binary_op(op, value_for(nullptr), var_for("language")), john).is_null()); + } } SECTION("regex matching handles invalid patterns") { diff --git a/tests/operators_test.cpp b/tests/operators_test.cpp index 53ed746..eeb2846 100644 --- a/tests/operators_test.cpp +++ b/tests/operators_test.cpp @@ -1,4 +1,5 @@ #include +#include #include "absmartly/json_expr/evaluator.h" #include "absmartly/json_expr/operators.h" @@ -514,43 +515,46 @@ TEST_CASE("InOperator", "[operators][in]") { Evaluator evaluator; json vars = {}; - // Operand order is haystack-first: [haystack, needle]. + // Operand order is haystack-first: [haystack, needle]. `contains` is an alias of `in`, so every + // case runs through both and must give the same result. + const std::string op = GENERATE(as{}, "in", "contains"); + CAPTURE(op); SECTION("string containment") { - json expr = {{"in", json::array({json{{"value", "abcdefghijk"}}, json{{"value", "abc"}}})}}; + json expr = {{op, json::array({json{{"value", "abcdefghijk"}}, json{{"value", "abc"}}})}}; REQUIRE(evaluator.evaluate(expr, vars) == true); - expr = {{"in", json::array({json{{"value", "abcdefghijk"}}, json{{"value", "def"}}})}}; + expr = {{op, json::array({json{{"value", "abcdefghijk"}}, json{{"value", "def"}}})}}; REQUIRE(evaluator.evaluate(expr, vars) == true); - expr = {{"in", json::array({json{{"value", "abcdefghijk"}}, json{{"value", "xxx"}}})}}; + expr = {{op, json::array({json{{"value", "abcdefghijk"}}, json{{"value", "xxx"}}})}}; REQUIRE(evaluator.evaluate(expr, vars) == false); } SECTION("null needle or haystack returns null") { - json expr = {{"in", json::array({json{{"value", "abcdefghijk"}}, json{{"value", nullptr}}})}}; + json expr = {{op, json::array({json{{"value", "abcdefghijk"}}, json{{"value", nullptr}}})}}; REQUIRE(evaluator.evaluate(expr, vars).is_null()); - expr = {{"in", json::array({json{{"value", nullptr}}, json{{"value", "abc"}}})}}; + expr = {{op, json::array({json{{"value", nullptr}}, json{{"value", "abc"}}})}}; REQUIRE(evaluator.evaluate(expr, vars).is_null()); } SECTION("empty array returns false") { - json expr = {{"in", json::array({json{{"value", json::array()}}, json{{"value", 1}}})}}; + json expr = {{op, json::array({json{{"value", json::array()}}, json{{"value", 1}}})}}; REQUIRE(evaluator.evaluate(expr, vars) == false); - expr = {{"in", json::array({json{{"value", json::array()}}, json{{"value", "1"}}})}}; + expr = {{op, json::array({json{{"value", json::array()}}, json{{"value", "1"}}})}}; REQUIRE(evaluator.evaluate(expr, vars) == false); - expr = {{"in", json::array({json{{"value", json::array()}}, json{{"value", true}}})}}; + expr = {{op, json::array({json{{"value", json::array()}}, json{{"value", true}}})}}; REQUIRE(evaluator.evaluate(expr, vars) == false); - expr = {{"in", json::array({json{{"value", json::array()}}, json{{"value", false}}})}}; + expr = {{op, json::array({json{{"value", json::array()}}, json{{"value", false}}})}}; REQUIRE(evaluator.evaluate(expr, vars) == false); } SECTION("null needle with array returns null") { - json expr = {{"in", json::array({json{{"value", json::array()}}, json{{"value", nullptr}}})}}; + json expr = {{op, json::array({json{{"value", json::array()}}, json{{"value", nullptr}}})}}; REQUIRE(evaluator.evaluate(expr, vars).is_null()); } @@ -558,16 +562,16 @@ TEST_CASE("InOperator", "[operators][in]") { json haystack01 = json::array({0, 1}); json haystack12 = json::array({1, 2}); - json expr = {{"in", json::array({json{{"value", haystack01}}, json{{"value", 2}}})}}; + json expr = {{op, json::array({json{{"value", haystack01}}, json{{"value", 2}}})}}; REQUIRE(evaluator.evaluate(expr, vars) == false); - expr = {{"in", json::array({json{{"value", haystack12}}, json{{"value", 0}}})}}; + expr = {{op, json::array({json{{"value", haystack12}}, json{{"value", 0}}})}}; REQUIRE(evaluator.evaluate(expr, vars) == false); - expr = {{"in", json::array({json{{"value", haystack12}}, json{{"value", 1}}})}}; + expr = {{op, json::array({json{{"value", haystack12}}, json{{"value", 1}}})}}; REQUIRE(evaluator.evaluate(expr, vars) == true); - expr = {{"in", json::array({json{{"value", haystack12}}, json{{"value", 2}}})}}; + expr = {{op, json::array({json{{"value", haystack12}}, json{{"value", 2}}})}}; REQUIRE(evaluator.evaluate(expr, vars) == true); } @@ -575,33 +579,21 @@ TEST_CASE("InOperator", "[operators][in]") { json haystackab = json{{"a", 1}, {"b", 2}}; json haystackbc = json{{"b", 2}, {"c", 3}, {"0", 100}}; - json expr = {{"in", json::array({json{{"value", haystackab}}, json{{"value", "c"}}})}}; + json expr = {{op, json::array({json{{"value", haystackab}}, json{{"value", "c"}}})}}; REQUIRE(evaluator.evaluate(expr, vars) == false); - expr = {{"in", json::array({json{{"value", haystackbc}}, json{{"value", "a"}}})}}; + expr = {{op, json::array({json{{"value", haystackbc}}, json{{"value", "a"}}})}}; REQUIRE(evaluator.evaluate(expr, vars) == false); - expr = {{"in", json::array({json{{"value", haystackbc}}, json{{"value", "b"}}})}}; + expr = {{op, json::array({json{{"value", haystackbc}}, json{{"value", "b"}}})}}; REQUIRE(evaluator.evaluate(expr, vars) == true); - expr = {{"in", json::array({json{{"value", haystackbc}}, json{{"value", "c"}}})}}; + expr = {{op, json::array({json{{"value", haystackbc}}, json{{"value", "c"}}})}}; REQUIRE(evaluator.evaluate(expr, vars) == true); - expr = {{"in", json::array({json{{"value", haystackbc}}, json{{"value", 0}}})}}; + expr = {{op, json::array({json{{"value", haystackbc}}, json{{"value", 0}}})}}; REQUIRE(evaluator.evaluate(expr, vars) == true); } - - SECTION("contains is an alias for in (haystack-first)") { - json haystack = json::array({1, 2, 3}); - json expr = {{"contains", json::array({json{{"value", haystack}}, json{{"value", 2}}})}}; - REQUIRE(evaluator.evaluate(expr, vars) == true); - - expr = {{"contains", json::array({json{{"value", "abcdefghijk"}}, json{{"value", "abc"}}})}}; - REQUIRE(evaluator.evaluate(expr, vars) == true); - - expr = {{"contains", json::array({json{{"value", haystack}}, json{{"value", 4}}})}}; - REQUIRE(evaluator.evaluate(expr, vars) == false); - } } TEST_CASE("MatchOperator", "[operators][match]") { diff --git a/tests/package_consumer/main.cpp b/tests/package_consumer/main.cpp index dfb5dc9..759d956 100644 --- a/tests/package_consumer/main.cpp +++ b/tests/package_consumer/main.cpp @@ -4,9 +4,27 @@ #include #include +#include int main() { absmartly::ContextData data; + // ContextData had one member in 1.0.0. Existing bindings must keep that shape. + auto& [experiments] = data; + const auto& [const_experiments] = std::as_const(data); + auto [copied_experiments] = data; + auto&& [moved_experiments] = std::move(data); + if (&experiments != &data.experiments || &const_experiments != &data.experiments || + &moved_experiments != &data.experiments || !copied_experiments.empty()) return 2; + absmartly::ExperimentData released; + released.name = "released"; + released.assignmentRules = "rules"; + auto& [id, name, unitType, iteration, seedHi, seedLo, split, seedStrictMode, trafficSeedHi, trafficSeedLo, + trafficSplit, fullOnVariant, audience, variants, audienceStrict, customFieldValues, application, + environment, assignmentRules] = released; + const auto& [const_id, const_name, cu, ci, csh, csl, cs, cssm, ctsh, ctsl, cts, cfov, ca, cv, cas, ccfv, capp, + cenv, const_rules] = std::as_const(released); + if (&name != &released.name || &assignmentRules != &released.assignmentRules || + &const_rules != &released.assignmentRules || name != "released") return 3; absmartly::ExperimentData exp; exp.id = 1; exp.name = "exp"; diff --git a/tests/public_headers_check.cpp b/tests/public_headers_check.cpp new file mode 100644 index 0000000..633526c --- /dev/null +++ b/tests/public_headers_check.cpp @@ -0,0 +1,5 @@ +// Compiled with strict warnings as errors (tests/CMakeLists.txt): the public headers must +// stay clean for consumers that embed the SDK with add_subdirectory/FetchContent and build +// with -Wfloat-equal -Werror. +#include +#include