diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f2dfb8..717cce1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,46 @@ ## Unreleased +### Fixed + +- **Shared variable keys exposed experiments the user never saw.** When two or + more experiments define the same variable key, `variable_value()` queued an + exposure for every candidate it visited on the way to the winner, including + experiments the unit was not in (a strict audience mismatch, no unit for the + experiment's unit type) and experiments that ended on the caller default. + Those users were recorded in experiments that never affected them. Both + `variable_value()` and `peek_variable_value()` could also return a value from + a later experiment when the winner's assigned arm did not define the key, so + the arm a user got decided which experiment they were counted in. This + affects anyone with two or more running experiments that share a variable + key. The rule now applied, matching the Java SDK: the candidates are the + experiments whose variants define the key, by experiment id ascending; the + winner is the first one the unit is assigned to (including a unit outside the + traffic split, which gets the control value), overridden into or + rule-assigned to; if the winner's variant does not define the key the caller + default is returned and no later experiment is tried; if no candidate + qualifies the default is returned. Only the winner is exposed, and + `peek_variable_value()` exposes nothing. This replaces the earlier rule + (shared with the JavaScript SDK) of exposing every candidate checked and + falling through to a later experiment when the key was missing. + + This also applies when only one experiment defines the key: a unit that is + not in it (a strict audience mismatch, or no unit for its unit type) gets the + default and is no longer exposed by `variable_value()`, so exposure counts + for such experiments can drop. `treatment()` still exposes it. An override to + a variant the experiment does not have now makes that experiment the winner + with the default value and an exposure, instead of falling through to a + later experiment's value. An override set before its experiment is loaded + now binds to that experiment once a refresh brings it in, so the value and + the exposure (id, unit type) come from the loaded experiment, whatever its + id; if it was already exposed before the refresh, it is exposed once more + with that data. An override already bound to an experiment that leaves and + returns unchanged is not exposed again. `variable_value()` and `treatment()` + return the value and variant they exposed even when an exposure event + handler changes overrides or refreshes the context. + +## 1.0.0 (2026-11-16) + ### Added - Ordered assignment rules (`ExperimentData::assignmentRules`). The first diff --git a/README.md b/README.md index e7249b4..80763f0 100644 --- a/README.md +++ b/README.md @@ -317,6 +317,10 @@ nlohmann::json show_banner = context.variable_value("show_banner", false); nlohmann::json banner_height = context.variable_value("banner_height", 200); ``` +#### Shared variable keys + +When several experiments define the same variable key, the experiments whose variants define it are checked in ascending experiment id order. The first one the user is in (assigned, overridden or rule-assigned) wins, and only that experiment is exposed. A user who is assigned but outside the traffic split still counts: they get the experiment's control (variant 0) value and are exposed to it. If the winner's assigned variant does not define the key, `variable_value()` and `peek_variable_value()` return your default rather than trying a later experiment. If the user is in none of them, both return your default and no exposure is recorded. + ### Peek at Treatment Variants Although generally not recommended, it is sometimes necessary to peek at a treatment or variable without triggering an exposure. The A/B Smartly SDK provides `peek()` and `peek_variable_value()` methods for that. diff --git a/include/absmartly/context.h b/include/absmartly/context.h index b6e6022..549b8dd 100644 --- a/include/absmartly/context.h +++ b/include/absmartly/context.h @@ -15,6 +15,7 @@ #include #include #include +#include #include namespace absmartly { @@ -132,6 +133,7 @@ class Context { friend struct ContextTestAccess; Assignment& get_or_create_assignment(const std::string& experiment_name); + std::pair variable_assignment(const std::string& key); void queue_exposure(const std::string& experiment_name, const Assignment& assignment); void build_index(); diff --git a/src/context.cpp b/src/context.cpp index 99d28ab..ffbc319 100644 --- a/src/context.cpp +++ b/src/context.cpp @@ -277,13 +277,15 @@ int Context::treatment(const std::string& experiment_name) { check_ready(true); 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; if (!assignment.exposed) { assignment.exposed = true; queue_exposure(experiment_name, assignment); } - return assignment.variant; + return variant; } int Context::peek(const std::string& experiment_name) { @@ -293,54 +295,58 @@ int Context::peek(const std::string& experiment_name) { return assignment.variant; } -nlohmann::json Context::variable_value(const std::string& key, const nlohmann::json& default_value) { - check_ready(true); - +// The candidates for a key are the experiments whose variants define it, by id ascending. The +// 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) { auto var_it = index_variables_.find(key); if (var_it == index_variables_.end()) { - return default_value; + return {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); - - if (assignment.has_variables) { - if (!assignment.exposed) { - assignment.exposed = true; - queue_exposure(experiment_name, assignment); - } - - if ((assignment.assigned || assignment.overridden || assignment.rule_override) && - assignment.variables.count(key) > 0) { - return assignment.variables.at(key); - } + if (assignment.assigned || assignment.overridden || assignment.rule_override) { + return {&experiment_name, &assignment}; } } - return default_value; + return {nullptr, nullptr}; } -nlohmann::json Context::peek_variable_value(const std::string& key, const nlohmann::json& default_value) { +nlohmann::json Context::variable_value(const std::string& key, const nlohmann::json& default_value) { check_ready(true); - auto var_it = index_variables_.find(key); - if (var_it == index_variables_.end()) { + auto [experiment_name, assignment] = variable_assignment(key); + if (assignment == nullptr) { return default_value; } - 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 value_it = assignment->variables.find(key); + nlohmann::json value = value_it != assignment->variables.end() ? value_it->second : default_value; - if (assignment.has_variables && - (assignment.assigned || assignment.overridden || assignment.rule_override) && - assignment.variables.count(key) > 0) { - return assignment.variables.at(key); - } + if (!assignment->exposed) { + assignment->exposed = true; + queue_exposure(*experiment_name, *assignment); } - return default_value; + 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; + if (assignment == nullptr) { + return default_value; + } + + auto value_it = assignment->variables.find(key); + return value_it != assignment->variables.end() ? value_it->second : default_value; } std::map> Context::variable_keys() { @@ -588,8 +594,32 @@ void Context::refresh(const ContextData& new_data) { // Cached assignments are kept (sticky): get_or_create_assignment() decides // per experiment whether a cached one is still valid against the new data. // An override stays valid while its variant is unchanged, as in JS. + // An override cached while its experiment was not loaded holds no experiment data, so when + // the experiment arrives it is dropped and the next read binds it to that data. One already + // bound to the same experiment data is kept, so it is not exposed again. + std::vector unloaded_overrides; + for (const auto& [name, assignment] : assignments_) { + if (assignment.overridden && index_.count(name) == 0) { + unloaded_overrides.push_back(name); + } + } + data_ = new_data; build_index(); + for (const auto& name : unloaded_overrides) { + auto exp_it = index_.find(name); + if (exp_it == index_.end()) { + continue; + } + const auto& existing = assignments_[name]; + const auto& exp_data = *exp_it->second.data; + bool variant_has_variables = existing.variant >= 0 && + static_cast(existing.variant) < exp_it->second.variables.size(); + if (existing.id != exp_data.id || existing.unit_type != exp_data.unitType || + existing.iteration != exp_data.iteration || existing.has_variables != variant_has_variables) { + assignments_.erase(name); + } + } hashes_.clear(); assigners_.clear(); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 7573df8..1b2a81f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -17,6 +17,7 @@ add_executable(absmartly_tests system_attributes_test.cpp assignment_rules_test.cpp http_integration_test.cpp + shared_variable_key_test.cpp ) target_link_libraries(absmartly_tests PRIVATE absmartly-sdk Catch2::Catch2WithMain) diff --git a/tests/shared_variable_key_test.cpp b/tests/shared_variable_key_test.cpp new file mode 100644 index 0000000..0998d68 --- /dev/null +++ b/tests/shared_variable_key_test.cpp @@ -0,0 +1,567 @@ +#include +#include +#include +#include + +#include + +using namespace absmartly; +using json = nlohmann::json; + +// Several experiments can define the same variable key. The candidates are the experiments +// whose variants define it, by experiment id ascending; the winner is the first one the unit is +// in (assigned, overridden or rule-assigned) and the value comes from its variant only. Only +// the winner is exposed: a candidate that was checked but did not win was never seen by the +// user. Mirrors the Java SDK's Context.getVariableAssignment. + +static const char* KEY = "banner.color"; +static const char* LOW = "exp_low"; +static const char* HIGH = "exp_high"; + +// A full-on experiment is assigned without hashing, so the winning arm is fixed by the fixture. +static ExperimentData make_exp(int id, const std::string& name, std::initializer_list configs, + int full_on_variant) { + ExperimentData exp; + exp.id = id; + exp.name = name; + exp.unitType = "session_id"; + exp.iteration = 1; + exp.seedHi = 3603515; + exp.seedLo = 233373850; + exp.trafficSeedHi = 449867249; + exp.trafficSeedLo = 455443629; + exp.trafficSplit = {0.0, 1.0}; + exp.fullOnVariant = full_on_variant; + exp.audience = nullptr; + int i = 0; + for (const auto& config : configs) { + ExperimentVariant variant; + variant.name = std::string(1, static_cast('A' + i++)); + variant.config = config.is_null() ? json(nullptr) : json(config.dump()); + exp.split.push_back(1.0 / static_cast(configs.size())); + exp.variants.push_back(variant); + } + return exp; +} + +static ExperimentData low_exp(int full_on_variant = 1) { + return make_exp(1, LOW, {nullptr, {{KEY, "low"}}}, full_on_variant); +} + +static ExperimentData high_exp(int full_on_variant = 1) { + return make_exp(2, HIGH, {nullptr, {{KEY, "high"}}}, full_on_variant); +} + +static void strict_mismatch(ExperimentData& exp) { + exp.audienceStrict = true; + exp.audience = json(R"({"filter":[{"eq":[{"var":"country"},{"value":"US"}]}]})"); +} + +static void missing_unit(ExperimentData& exp) { + exp.unitType = "device_id"; + exp.fullOnVariant = 0; +} + +static ContextData data_of(std::initializer_list experiments) { + ContextData data; + // Reversed so candidate order must come from the id, not from the payload order. + for (auto it = std::rbegin(experiments); it != std::rend(experiments); ++it) { + data.experiments.push_back(*it); + } + return data; +} + +static ContextConfig make_config() { + ContextConfig config; + config.publish_delay = -1; + config.refresh_period = 0; + config.units = {{"session_id", "e791e240fcd3df7d238cfc285f475e8152fcc0ec"}}; + return config; +} + +static std::vector exposed_names(Context& ctx) { + std::vector names; + for (const auto& exposure : ctx.publish().exposures) { + names.push_back(exposure.name); + } + return names; +} + +static json assign_rule_to(int variant) { + return {{"rules", json::array({{{"name", "all"}, {"type", "assign"}, {"conditions", nullptr}, + {"environments", json::array()}, {"variant", variant}}})}}; +} + +TEST_CASE("Shared variable key: an unassigned lower-id candidate is skipped without exposure", + "[context][shared-variable-key]") { + auto low = low_exp(); + SECTION("strict audience mismatch") { strict_mismatch(low); } + SECTION("no unit for its unit type") { missing_unit(low); } + + Context ctx(make_config(), data_of({low, high_exp()})); + REQUIRE(ctx.variable_value(KEY, "default") == "high"); + REQUIRE(ctx.pending() == 1); + REQUIRE(exposed_names(ctx) == std::vector{HIGH}); +} + +TEST_CASE("Shared variable key: a losing candidate is still exposed by its own treatment()", + "[context][shared-variable-key]") { + // Checking a candidate must not mark it exposed, or a later treatment() would skip it. + auto low = low_exp(); + strict_mismatch(low); + Context ctx(make_config(), data_of({low, high_exp()})); + + REQUIRE(ctx.variable_value(KEY, "default") == "high"); + REQUIRE(ctx.pending() == 1); + REQUIRE(ctx.treatment(LOW) == 0); + REQUIRE(ctx.pending() == 2); + REQUIRE(exposed_names(ctx) == std::vector{HIGH, LOW}); +} + +TEST_CASE("Shared variable key: an override on an experiment that is not loaded is exposed once by treatment()", + "[context][shared-variable-key]") { + Context ctx(make_config(), data_of({high_exp()})); + ctx.set_override("not_running", 1); + + for (int i = 0; i < 5; ++i) { + REQUIRE(ctx.treatment("not_running") == 1); + } + REQUIRE(ctx.pending() == 1); +} + +TEST_CASE("Shared variable key: an overridden winner with experiment id 0 is exposed once", + "[context][shared-variable-key]") { + Context ctx(make_config(), data_of({make_exp(0, "exp_zero", {nullptr, {{KEY, "zero"}}}, 1)})); + ctx.set_override("exp_zero", 1); + + for (int i = 0; i < 3; ++i) { + REQUIRE(ctx.treatment("exp_zero") == 1); + REQUIRE(ctx.variable_value(KEY, "default") == "zero"); + } + REQUIRE(ctx.pending() == 1); +} + +TEST_CASE("Shared variable key: treatment() returns the variant it exposed when the logger overrides", + "[context][shared-variable-key]") { + struct OverrideOnExposure : ContextEventLogger { + bool done = false; + void handle_event(Context& context, const std::string& event_type, const json&) override { + if (event_type == "exposure" && !done) { + done = true; + context.set_override(HIGH, 0); + context.peek(HIGH); + } + } + }; + auto logger = std::make_shared(); + Context ctx(make_config(), data_of({high_exp()}), logger); + + REQUIRE(ctx.treatment(HIGH) == 1); + REQUIRE(logger->done); + REQUIRE(ctx.peek(HIGH) == 0); +} + +TEST_CASE("Shared variable key: a candidate exposed by its own treatment() does not win", + "[context][shared-variable-key]") { + auto low = low_exp(); + strict_mismatch(low); + Context ctx(make_config(), data_of({low, high_exp()})); + + ctx.treatment(LOW); + REQUIRE(ctx.variable_value(KEY, "default") == "high"); + REQUIRE(exposed_names(ctx) == std::vector{LOW, HIGH}); +} + +TEST_CASE("Shared variable key: the value is read before the exposure logger runs", + "[context][shared-variable-key]") { + // A synchronous logger can re-resolve the winner; the read returns the value of the + // assignment it exposed, not the one the logger left behind. + struct OverrideOnExposure : ContextEventLogger { + bool done = false; + void handle_event(Context& context, const std::string& event_type, const json&) override { + if (event_type == "exposure" && !done) { + done = true; + context.set_override(HIGH, 0); + context.peek(HIGH); + } + } + }; + auto logger = std::make_shared(); + Context ctx(make_config(), data_of({high_exp()}), logger); + + REQUIRE(ctx.variable_value(KEY, "default") == "high"); + REQUIRE(logger->done); + REQUIRE(ctx.peek_variable_value(KEY, "default") == "default"); +} + +TEST_CASE("Shared variable key: the winner's exposure is queued once", "[context][shared-variable-key]") { + auto low = low_exp(); + strict_mismatch(low); + Context ctx(make_config(), data_of({low, high_exp()})); + + REQUIRE(ctx.variable_value(KEY, "default") == "high"); + REQUIRE(ctx.variable_value(KEY, "default") == "high"); + + auto event = ctx.publish(); + REQUIRE(event.exposures.size() == 1); + REQUIRE(event.exposures[0].id == 2); + REQUIRE(event.exposures[0].name == HIGH); + REQUIRE(event.exposures[0].variant == 1); + REQUIRE(event.exposures[0].assigned); +} + +TEST_CASE("Shared variable key: the lowest-id assigned candidate wins", "[context][shared-variable-key]") { + Context ctx(make_config(), data_of({low_exp(), high_exp()})); + REQUIRE(ctx.variable_value(KEY, "default") == "low"); + REQUIRE(exposed_names(ctx) == std::vector{LOW}); +} + +TEST_CASE("Shared variable key: an assigned candidate wins even when it is not eligible or mismatches", + "[context][shared-variable-key]") { + SECTION("traffic-excluded: assigned, not eligible, control value") { + auto low = make_exp(1, LOW, {{{KEY, "low-control"}}, {{KEY, "low"}}}, 0); + low.trafficSplit = {1.0, 0.0}; + Context ctx(make_config(), data_of({low, high_exp()})); + REQUIRE(ctx.variable_value(KEY, "default") == "low-control"); + auto event = ctx.publish(); + REQUIRE(event.exposures.size() == 1); + REQUIRE(event.exposures[0].name == LOW); + REQUIRE(event.exposures[0].assigned); + REQUIRE_FALSE(event.exposures[0].eligible); + } + + SECTION("non-strict audience mismatch") { + auto low = low_exp(); + low.audience = json(R"({"filter":[{"eq":[{"var":"country"},{"value":"US"}]}]})"); + Context ctx(make_config(), data_of({low, high_exp()})); + REQUIRE(ctx.variable_value(KEY, "default") == "low"); + auto event = ctx.publish(); + REQUIRE(event.exposures.size() == 1); + REQUIRE(event.exposures[0].name == LOW); + REQUIRE(event.exposures[0].audienceMismatch); + } +} + +TEST_CASE("Shared variable key: a custom-assigned candidate wins", "[context][shared-variable-key]") { + auto low = low_exp(); + low.fullOnVariant = 0; + low.split = {1.0, 0.0}; + Context ctx(make_config(), data_of({low, high_exp()})); + ctx.set_custom_assignment(LOW, 1); + + REQUIRE(ctx.peek_variable_value(KEY, "default") == "low"); + REQUIRE(ctx.pending() == 0); + REQUIRE(ctx.variable_value(KEY, "default") == "low"); + auto event = ctx.publish(); + REQUIRE(event.exposures.size() == 1); + REQUIRE(event.exposures[0].name == LOW); + REQUIRE(event.exposures[0].custom); +} + +TEST_CASE("Shared variable key: a custom assignment alone does not make an unassigned candidate win", + "[context][shared-variable-key]") { + auto low = low_exp(); + low.fullOnVariant = 0; + strict_mismatch(low); + Context ctx(make_config(), data_of({low, high_exp()})); + ctx.set_custom_assignment(LOW, 1); + + REQUIRE(ctx.peek_variable_value(KEY, "default") == "high"); + REQUIRE(ctx.pending() == 0); + REQUIRE(ctx.variable_value(KEY, "default") == "high"); + REQUIRE(exposed_names(ctx) == std::vector{HIGH}); +} + +TEST_CASE("Shared variable key: a key defined by one experiment exposes only a unit in it", + "[context][shared-variable-key]") { + auto low = low_exp(); + SECTION("strict audience mismatch") { strict_mismatch(low); } + SECTION("no unit for its unit type") { missing_unit(low); } + + Context ctx(make_config(), data_of({low})); + REQUIRE(ctx.variable_value(KEY, "default") == "default"); + REQUIRE(ctx.pending() == 0); + ctx.treatment(LOW); + REQUIRE(ctx.pending() == 1); +} + +TEST_CASE("Shared variable key: a winner whose variant lacks the key gives the default", + "[context][shared-variable-key]") { + // The low-id experiment is assigned to variant 0, which does not define the key. Its value + // is the caller default; a later candidate must not supply one, or the arm the user got + // would decide which experiment they are counted in. + auto low = low_exp(); + SECTION("traffic-assigned arm") { + low.fullOnVariant = 0; + low.split = {1.0, 0.0}; + } + SECTION("full-on arm") { + // The key is defined only by variant 2, so the experiment is still a candidate. + low = make_exp(1, LOW, {nullptr, nullptr, {{KEY, "low"}}}, 1); + } + + Context ctx(make_config(), data_of({low, high_exp()})); + REQUIRE(ctx.peek_variable_value(KEY, "default") == "default"); + REQUIRE(ctx.pending() == 0); + REQUIRE(ctx.variable_value(KEY, "default") == "default"); + REQUIRE(exposed_names(ctx) == std::vector{LOW}); +} + +TEST_CASE("Shared variable key: no candidate assigned gives the default and no exposure", + "[context][shared-variable-key]") { + auto low = low_exp(); + auto high = high_exp(); + strict_mismatch(low); + missing_unit(high); + Context ctx(make_config(), data_of({low, high})); + + REQUIRE(ctx.variable_value(KEY, "default") == "default"); + REQUIRE(ctx.pending() == 0); +} + +TEST_CASE("Shared variable key: peek exposes nothing", "[context][shared-variable-key]") { + auto low = low_exp(); + strict_mismatch(low); + Context ctx(make_config(), data_of({low, high_exp()})); + + REQUIRE(ctx.peek_variable_value(KEY, "default") == "high"); + REQUIRE(ctx.pending() == 0); +} + +TEST_CASE("Shared variable key: overrides", "[context][shared-variable-key]") { + SECTION("an override makes an unassigned candidate the winner") { + auto low = low_exp(); + missing_unit(low); + Context ctx(make_config(), data_of({low, high_exp()})); + ctx.set_override(LOW, 1); + REQUIRE(ctx.variable_value(KEY, "default") == "low"); + REQUIRE(exposed_names(ctx) == std::vector{LOW}); + } + + SECTION("an override to an arm without the key gives the default") { + Context ctx(make_config(), data_of({low_exp(), high_exp()})); + ctx.set_override(LOW, 0); + REQUIRE(ctx.variable_value(KEY, "default") == "default"); + REQUIRE(exposed_names(ctx) == std::vector{LOW}); + } + + SECTION("an override to an unknown variant still wins and gives the default") { + Context ctx(make_config(), data_of({low_exp(), high_exp()})); + ctx.set_override(LOW, 11); + REQUIRE(ctx.variable_value(KEY, "default") == "default"); + REQUIRE(exposed_names(ctx) == std::vector{LOW}); + } + + SECTION("an override on the higher-id candidate does not beat an assigned lower-id one") { + Context ctx(make_config(), data_of({low_exp(), high_exp()})); + ctx.set_override(HIGH, 1); + REQUIRE(ctx.variable_value(KEY, "default") == "low"); + REQUIRE(exposed_names(ctx) == std::vector{LOW}); + } + + SECTION("an override on the higher-id candidate wins over an unassigned lower-id one") { + auto low = low_exp(); + strict_mismatch(low); + auto high = high_exp(); + missing_unit(high); + Context ctx(make_config(), data_of({low, high})); + ctx.set_override(HIGH, 1); + REQUIRE(ctx.variable_value(KEY, "default") == "high"); + REQUIRE(exposed_names(ctx) == std::vector{HIGH}); + } +} + +TEST_CASE("Shared variable key: assignment rules", "[context][shared-variable-key]") { + SECTION("a rule makes an otherwise unassigned candidate the winner") { + auto low = low_exp(); + strict_mismatch(low); + low.assignmentRules = assign_rule_to(1).dump(); + Context ctx(make_config(), data_of({low, high_exp()})); + REQUIRE(ctx.variable_value(KEY, "default") == "low"); + auto event = ctx.publish(); + REQUIRE(event.exposures.size() == 1); + REQUIRE(event.exposures[0].name == LOW); + REQUIRE(event.exposures[0].ruleOverride); + } + + SECTION("a rule-won winner is exposed once across reads") { + auto low = low_exp(); + strict_mismatch(low); + low.assignmentRules = assign_rule_to(1).dump(); + Context ctx(make_config(), data_of({low, high_exp()})); + REQUIRE(ctx.variable_value(KEY, "default") == "low"); + REQUIRE(ctx.variable_value(KEY, "default") == "low"); + REQUIRE(ctx.pending() == 1); + } + + SECTION("a rule to an arm without the key gives the default") { + auto low = low_exp(); + low.assignmentRules = assign_rule_to(0).dump(); + Context ctx(make_config(), data_of({low, high_exp()})); + REQUIRE(ctx.variable_value(KEY, "default") == "default"); + REQUIRE(exposed_names(ctx) == std::vector{LOW}); + } + + SECTION("an override beats a rule on the same candidate") { + auto low = low_exp(); + low.assignmentRules = assign_rule_to(1).dump(); + Context ctx(make_config(), data_of({low, high_exp()})); + ctx.set_override(LOW, 0); + REQUIRE(ctx.variable_value(KEY, "default") == "default"); + auto event = ctx.publish(); + REQUIRE(event.exposures.size() == 1); + REQUIRE(event.exposures[0].name == LOW); + REQUIRE(event.exposures[0].overridden); + REQUIRE_FALSE(event.exposures[0].ruleOverride); + } +} + +TEST_CASE("Shared variable key: falsy values are values, a missing key is not", + "[context][shared-variable-key]") { + for (const auto& value : {json(nullptr), json(false), json(0), json(""), json::array(), json::object()}) { + auto low = low_exp(); + strict_mismatch(low); + auto high = make_exp(2, HIGH, {nullptr, {{KEY, value}}}, 1); + Context ctx(make_config(), data_of({low, high})); + + CAPTURE(value.dump()); + REQUIRE(ctx.peek_variable_value(KEY, "default") == value); + REQUIRE(ctx.variable_value(KEY, "default") == value); + REQUIRE(exposed_names(ctx) == std::vector{HIGH}); + } +} + +TEST_CASE("Shared variable key: the winner follows attribute changes and refreshes", + "[context][shared-variable-key]") { + SECTION("an attribute that matches the strict audience makes the lower-id candidate win") { + auto low = low_exp(); + strict_mismatch(low); + Context ctx(make_config(), data_of({low, high_exp()})); + REQUIRE(ctx.variable_value(KEY, "default") == "high"); + + ctx.set_attribute("country", "US"); + REQUIRE(ctx.variable_value(KEY, "default") == "low"); + REQUIRE(exposed_names(ctx) == std::vector{HIGH, LOW}); + } + + SECTION("a refresh that removes the winner hands the key to the next candidate") { + Context ctx(make_config(), data_of({low_exp(), high_exp()})); + REQUIRE(ctx.variable_value(KEY, "default") == "low"); + + ctx.refresh(data_of({high_exp()})); + REQUIRE(ctx.variable_value(KEY, "default") == "high"); + REQUIRE(exposed_names(ctx) == std::vector{LOW, HIGH}); + } + + SECTION("an override cached before its experiment arrives binds to it on refresh") { + // Experiment id 0 is valid, so binding must not depend on the id. + int id = GENERATE(1, 0); + auto low = make_exp(id, LOW, {nullptr, {{KEY, "low"}}}, 1); + low.iteration = 3; + Context ctx(make_config(), data_of({high_exp()})); + ctx.set_override(LOW, 1); + ctx.treatment(LOW); + + ctx.refresh(data_of({low, high_exp()})); + REQUIRE(ctx.variable_value(KEY, "default") == "low"); + REQUIRE(ctx.treatment(LOW) == 1); + auto event = ctx.publish(); + REQUIRE(event.exposures.size() == 2); + REQUIRE(event.exposures[1].name == LOW); + REQUIRE(event.exposures[1].id == id); + REQUIRE(event.exposures[1].unit == "session_id"); + } + + SECTION("an override on an experiment that stays unloaded across refreshes is exposed once") { + Context ctx(make_config(), data_of({high_exp()})); + ctx.set_override(LOW, 1); + ctx.treatment(LOW); + ctx.refresh(data_of({high_exp()})); + ctx.treatment(LOW); + ctx.refresh(data_of({high_exp()})); + ctx.treatment(LOW); + REQUIRE(ctx.pending() == 1); + } + + SECTION("a bound override whose experiment leaves and returns unchanged is not exposed again") { + Context ctx(make_config(), data_of({low_exp(), high_exp()})); + ctx.set_override(LOW, 1); + REQUIRE(ctx.treatment(LOW) == 1); + ctx.refresh(data_of({high_exp()})); + ctx.treatment(LOW); + ctx.refresh(data_of({low_exp(), high_exp()})); + REQUIRE(ctx.treatment(LOW) == 1); + REQUIRE(ctx.variable_value(KEY, "default") == "low"); + REQUIRE(exposed_names(ctx) == std::vector{LOW}); + } + + SECTION("an override to a variant one past the last that leaves and returns is not exposed again") { + Context ctx(make_config(), data_of({low_exp(), high_exp()})); + ctx.set_override(LOW, 2); + REQUIRE(ctx.treatment(LOW) == 2); + ctx.refresh(data_of({high_exp()})); + ctx.refresh(data_of({low_exp(), high_exp()})); + REQUIRE(ctx.treatment(LOW) == 2); + REQUIRE(ctx.pending() == 1); + } + + SECTION("a bound override whose experiment returns changed binds to the new data") { + auto returned = low_exp(); + int field = GENERATE(0, 1, 2); + if (field == 0) returned.id = 7; + if (field == 1) returned.iteration = 4; + if (field == 2) returned.unitType = "user_id"; + auto config = make_config(); + config.units["user_id"] = "u1"; + Context ctx(config, data_of({low_exp(), high_exp()})); + ctx.set_override(LOW, 1); + ctx.treatment(LOW); + ctx.refresh(data_of({high_exp()})); + ctx.refresh(data_of({returned, high_exp()})); + + REQUIRE(ctx.treatment(LOW) == 1); + auto event = ctx.publish(); + REQUIRE(event.exposures.size() == 2); + REQUIRE(event.exposures[1].id == returned.id); + REQUIRE(event.exposures[1].unit == returned.unitType); + } + + SECTION("an override cached before load binds when only the variant variables differ") { + // Id 0, no unit type and iteration 0 match the placeholder's empty experiment data. + auto zero = make_exp(0, "exp_zero", {nullptr, {{KEY, "zero"}}}, 1); + zero.unitType = ""; + zero.iteration = 0; + Context ctx(make_config(), data_of({high_exp()})); + ctx.set_override("exp_zero", 1); + ctx.treatment("exp_zero"); + + ctx.refresh(data_of({zero})); + REQUIRE(ctx.variable_value(KEY, "default") == "zero"); + } + + SECTION("a logger that refreshes during the winner's exposure does not disturb the read") { + // The refresh replaces the experiment data the resolver walked, so the read must not + // touch the candidate list after queueing an exposure. The lower-id candidate is checked + // first and loses; a resolver that exposed it and kept walking would read freed data. + struct RefreshOnExposure : ContextEventLogger { + ContextData next; + bool refreshed = false; + void handle_event(Context& context, const std::string& event_type, const json&) override { + if (event_type == "exposure" && !refreshed) { + refreshed = true; + context.refresh(next); + } + } + }; + auto logger = std::make_shared(); + logger->next = data_of({}); + auto low = low_exp(); + strict_mismatch(low); + Context ctx(make_config(), data_of({low, high_exp()}), logger); + + REQUIRE(ctx.variable_value(KEY, "default") == "high"); + REQUIRE(logger->refreshed); + REQUIRE(ctx.variable_value(KEY, "default") == "default"); + REQUIRE(exposed_names(ctx) == std::vector{HIGH}); + } +}