diff --git a/CHANGELOG.md b/CHANGELOG.md index d1694c3..1c2f98a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,16 @@ - Holdouts, evaluated like the JS SDK. Context data may carry `holdouts` (each with `id`, `name`, `iteration`, `seedHi`, `seedLo` and `split`), and an experiment lists the holdouts covering it in `holdoutIds`. Each covering holdout places the unit in an arm, drawn from the holdout's `split` and seeds with the covered experiment's unit, and kept for the context while the holdout's `iteration` is unchanged. Arm 0 holds the unit out of the experiment; in a holdout with three arms, arm 1 holds the unit out only of experiments that are not full-on. A unit held out by any of its holdouts gets the control variant (`assigned` false), and audience, full-on, traffic and custom assignments do not apply. A variable read returns the held-out experiment's control value only when no assigned or overridden experiment defining the same key wins it. The held-out experiment publishes no exposure of its own, unless an override or a matching assignment rule chose its variant: both still win over the holdout. The first treatment or variable read of a covered experiment queues each holdout's exposure, named after the holdout, with the arm as its variant. That happens once per holdout, unit type and holdout iteration, however many reads or covered experiments follow; a new iteration is a new exposure. While the covered experiment's unit is not set, a holdout neither holds the unit out nor publishes. `peek_treatment` and `peek_variable_value` publish nothing. Payloads without holdouts are assigned and published exactly as before. - `ContextData.holdouts`, `Experiment.holdoutIds` and `Experiment.holdoutType` (all default `None`) and `sdk.json.holdout.Holdout`. Holdout entries may be the dicts the default deserializer produces, any `Mapping`, or objects with the same attributes; entries without a non-empty `split`, malformed entries (for example ids, seeds or split values that are not JSON numbers) and unknown fields are ignored. +### Fixed +- Shared variable keys: only the winning experiment is exposed. When two or more running experiments define the same variable key, `get_variable_value` queued an exposure for every experiment it checked on the way to the value, including ones the unit was not in (a strict audience mismatch, or a unit type that is not set for an experiment that is not full-on), so those users were recorded in experiments they never saw. And when the first experiment the unit was in had given it a variant without the key, the read fell through to the next experiment, so which experiment supplied the value (and was exposed) depended on the arm the unit got, biasing both experiments. Anyone with two or more running experiments sharing a variable key is affected; their exposure counts for the losing experiments drop after upgrading. So is anyone reading a key that only one experiment defines when the unit is not in it: a strict audience mismatch or a unit type that is not set used to be exposed by `get_variable_value` (a strict mismatch with `audienceMismatch` true) and now nothing wins the key, so no experiment exposure is published. A visited candidate can still publish its holdouts’ exposures when its unit is set. `get_treatment` still exposes such an experiment. The rule now applied, as in the Java SDK: the candidates are the experiments defining the key in any variant, in id order; the first one the unit is assigned to, overridden in or rule-assigned to wins; if the winner's variant lacks the key the default is returned; only the winner is exposed. When no candidate wins, the first held-out candidate supplies its control value, else the default is returned with no exposure. `peek_variable_value` resolves the same winner and exposes nothing. Holdout exposures are unchanged in kind: each candidate checked still publishes its holdouts' exposures, now before the winner's own exposure. An overridden or rule-assigned held-out experiment now wins the key like any other override or rule, so its variant lacking the key returns the default instead of a later experiment's value. + ### Changed +- Exposure counts change for experiments read with `get_variable_value`: an experiment the unit is not in (a strict audience mismatch, or a unit type that is not set for an experiment that is not full-on) is no longer exposed by a variable read, even when it is the only experiment defining the key, and an experiment that is checked for a shared key but does not win it is no longer exposed, and a winner whose variant lacks the key returns the default instead of a later experiment's value. See Fixed. This includes an override to a variant number the experiment does not have: the overridden experiment wins the key and is exposed, and the default is returned (0.3.0 skipped it and used the next experiment). +- A variable read stays consistent across the context lifecycle: when `set_unit` adds a unit while the read is checking the key's experiments, the read checks the key again before exposing the winner, and if it never sees one consistent state within its attempts it returns the default without exposing any winner (holdout exposures of experiments it had already checked may already have been published, once each); an experiment a concurrent `refresh` removed never wins the key (a refresh during the read makes it check the key again, `peek_variable_value` included); and the built-in queue accepts the winner together with its holdouts, so a concurrent close publishes both or neither. +- An override set for an experiment the context data does not have yet is exposed again with the experiment's real id once a refresh adds that experiment (0.3.0 kept the first exposure, queued with id 0). An override already exposed for a present experiment is still not exposed again when a refresh removes and restores it, or changes its id, as long as the cached override stays valid (a refresh that changes the experiment's holdouts or their iteration rebuilds it, which publishes a new exposure as for any rebuilt assignment). +- A warm `get_variable_value` is slightly slower (about 7% for a single candidate in a CPython microbenchmark, about 0.4 µs) because each read now checks for a concurrent refresh or `set_unit` before exposing anything. `get_treatment` is unchanged. +- A `queue_exposure` override that returns `False` (declines) is called once per read again, as in 0.3.0, and the read still returns the variant's value; a retry happens only when `set_unit` actually retired the experiment. +- A `queue_exposure` override that raises while being offered a holdout exposure no longer stops the remaining holdout exposures of that read (from `get_treatment` or `get_variable_value`): every one is offered and the first error is raised afterwards, as in the Java SDK. - Payloads with `holdouts` change assignment for held-out units. 0.3.0 ignored holdouts, so a unit the backend holds out still got its experiment's variant and an experiment exposure. From 0.4.0 that unit gets the control variant, and the holdout's exposure replaces the experiment's. Units that are not held out keep their variants, but their reads of covered experiments now also publish the holdout exposures. Payloads without holdouts are unaffected. - The `X-Agent` header and `sdk_version` report `0.4.0`. diff --git a/README.md b/README.md index fdddc49..e8f6e9b 100644 --- a/README.md +++ b/README.md @@ -229,6 +229,16 @@ else: button_color = context.get_variable_value("button.color", "red") ``` +#### Shared Variable Keys + +When several experiments define the same variable key (in any of their variants), `get_variable_value` and `peek_variable_value` check them in experiment id order and use the first one the unit is in: assigned (including a unit outside traffic, which gets control), overridden with `set_override`, or chosen by an assignment rule. That experiment wins the key: + +- The value comes from the winner's variant. If that variant does not define the key, the default you passed is returned; later experiments are not consulted, so which arm the unit got never changes which experiment is used. +- Only the winner is exposed. Experiments that were checked and lost (for example a strict audience mismatch, or a unit type that is not set for an experiment that needs it for traffic assignment) get no exposure. A full-on experiment does not need its unit, so it can win and be exposed with the unit unset. +- This also applies when only one experiment defines the key: if the unit is not in it (a strict audience mismatch, or a unit type that is not set for an experiment that is not full-on), nothing wins, the default is returned and no experiment exposure is published. A non-suppressing holdout can still publish its exposure when the candidate’s unit is set. `get_treatment` still exposes that experiment. +- If no experiment wins, a held-out experiment defining the key supplies its control value (see [Holdouts](#holdouts)); otherwise the default is returned and no experiment exposure is published (the checked experiments' holdouts can still publish theirs). +- `peek_variable_value` resolves the same winner and exposes nothing. + #### Listing Variable Keys `get_variable_keys()` maps each variable key to the name of one experiment that defines it, keeping the v0.2.4 shape. When several experiments define the same key, it returns the lowest-id experiment (the first one variable lookups visit). Use `get_variable_keys_all()` to get every experiment defining each key, in experiment id order, matching the JavaScript SDK's `variableKeys()`. @@ -297,7 +307,7 @@ treatment = context.get_treatment("exp_covered_by_holdout") # 0 when held out color = context.get_variable_value("button.color", "red") # control value when held out ``` -Unless an override or a matching assignment rule chose its variant, the held-out experiment publishes no exposure of its own. The first read of a covered experiment (`get_treatment`, `get_variable_value`) instead publishes each holdout's exposure, named after the holdout, with the unit's arm as its variant. Each holdout is published once per unit type and holdout iteration, however many covered experiments are read; a new iteration publishes again. A holdout needs the covered experiment's unit: while that unit is not set, the holdout neither holds the unit out nor publishes. `peek_treatment` and `peek_variable_value` publish nothing. +Unless an override or a matching assignment rule chose its variant, the held-out experiment publishes no exposure of its own. The first read of a covered experiment (`get_treatment`, `get_variable_value`) instead publishes each holdout's exposure, named after the holdout, with the unit's arm as its variant. Each holdout is published once per unit type and holdout iteration, however many covered experiments are read; a new iteration publishes again. A variable read checks every experiment defining the key up to the winner (see [Shared Variable Keys](#shared-variable-keys)), and each one it checks publishes its holdouts' exposures, even when it does not win; its own exposure is published only if it wins. A holdout needs the covered experiment's unit: while that unit is not set, the holdout neither holds the unit out nor publishes. `peek_treatment` and `peek_variable_value` publish nothing. An override (`set_override`) or a matching assignment rule still decides the variant of a held-out unit, and the holdout exposures are still published. Custom assignments, audiences, full-on variants and traffic do not apply to a held-out unit. diff --git a/sdk/context.py b/sdk/context.py index 898a817..9df5e7a 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -84,6 +84,9 @@ def __init__(self): # holdout exposure of this assignment, so a later read of the same # experiment finishes them (e.g. after a failed close reopens). self.holdouts_pending: bool = False + # Set once every pinned arm is exposed; pinned arms never change, + # so it is never cleared (see Context._expose_holdouts). + self.holdouts_exposed: bool = False class ExperimentVariables: @@ -323,6 +326,10 @@ def __init__(self, self._system_attributes["environment"] = environment self.units = {} + # Bumped by set_unit whenever a unit is added (and unexposed + # assignments for it are retired), so a variable read can tell that + # a unit arrived during its walk. + self._units_seq = 0 self.index = {} self.index_variables = {} self.context_custom_fields = {} @@ -487,6 +494,7 @@ def set_unit(self, unit_type: str, uid): added = unit_type not in self.units self.units[unit_type] = uid if added: + self._units_seq += 1 # Like the JS SDK's unit(): an unexposed assignment for this # unit type was resolved while the unit was missing, so drop # it and let the next read resolve it with the unit. Exposed @@ -1061,42 +1069,150 @@ def peek_variable_value(self, key: str, default_value: object): return self._variable_value(key, default_value, False) def _variable_value(self, key: str, default_value: object, expose: bool, - attempt: int = 1): - # Port of the JS SDK's _variableValue/_peekVariable: walk every - # experiment defining the key (sorted by id) and return the value from - # the first one the unit is assigned to or overridden in, queuing an - # exposure for each experiment visited on the way. - # A held-out experiment never wins the key over an assigned one, but - # when nothing else does its control value is returned instead of - # the default (JS _resolveVariableValue). The first held-out - # candidate is kept even if it lacks the key. - experiments = Concurrency.get_rw( - self.data_lock, self.index_variables, key) or [] + attempt: int = 1, offered=None): + retry = attempt < _MAX_EXPOSURE_ATTEMPTS + if offered is None and expose: + # Holdout arms this public read offered a queue_exposure + # override, kept across attempts so a declined arm is offered + # once per read (the next read offers it again). + offered = set() + assignment, invalidated, deferred = self._variable_assignment( + key, expose, retry, offered) + if invalidated: + if retry: + # set_unit added a unit or a refresh replaced the data during + # the walk, so the key may resolve differently: walk it again + # before exposing any experiment (peek too, so it never + # returns a value no single state would give). + return self._variable_value(key, default_value, expose, + attempt + 1, offered) + # Out of attempts and still not one coherent state: neither + # payload alone gave this winner, so return the default and + # expose nothing. + return default_value + if expose and assignment is not None and \ + not assignment.exposed.value and \ + not self._expose_winner(assignment): + if retry: + # set_unit retired the winner in between: walk it again. + return self._variable_value(key, default_value, expose, + attempt + 1, offered) + # Out of attempts with the winner still retired: like an + # invalidated walk, return the default rather than the value of + # a winner that was never exposed. + return default_value + for loser in deferred: + # Losers whose shared arms were left for the winner's section: + # once those are exposed, later reads skip them. + if not self._holdouts_unexposed(loser): + loser.holdouts_exposed = True + loser.holdouts_pending = False + if assignment is not None and assignment.variables is not None and \ + key in assignment.variables: + return assignment.variables[key] + return default_value + + def _expose_winner(self, assignment: Assignment): + # The built-in queue accepts the winner and its holdouts in one + # event_lock section (holdouts first, as on the walk), so a close + # cannot publish one without the other. A queue_exposure override + # was already offered the holdouts by the walk. + if getattr(self.queue_exposure, "__func__", None) is \ + Context.queue_exposure: + return self._expose(assignment, holdouts_first=True) + return self._expose(assignment, offer_holdouts=False) + + def _variable_assignment(self, key: str, expose: bool, + retry: bool = False, offered=None): + # Port of the Java SDK's getVariableAssignment: the candidates are + # the experiments defining the key in any variant, in id order, and + # the first one the unit is assigned to, overridden in or + # rule-assigned to wins. Only the winner is exposed, by the caller: + # a candidate that was checked and lost publishes no exposure of its + # own, though its holdouts still fire, whether or not anything wins + # (a held-out unit and a not held-out one fire the same holdouts). + # The winner's variant decides alone: if it lacks the key, the + # caller gets the default and later candidates are not consulted. A + # held-out candidate never wins over another, but when none wins the + # first held-out one supplies its control variant (and is exposed). + # A raising queue_exposure hook does not stop the walk: the first + # error is raised once every visited candidate was offered, as in + # Java. Returns the winner, whether set_unit added a unit or a + # refresh replaced the data during the walk (which makes the caller + # walk again or, out of attempts, return the default; an invalidated + # walk offers no holdouts), and the losers whose shared holdout arms + # were left for the winner's exposure. + units_seq = self._units_seq + try: + # The write side, like Concurrency.get_rw: this lock's read side + # costs more for a single short section. + self.data_lock.acquire_write() + index = self.index + experiments = self.index_variables.get(key) or [] + finally: + self.data_lock.release_write() + winner = None suppressed_fallback = None + pending = None + deferred = () for experiment in list(experiments): assignment = self.get_assignment(experiment.data.name) - if assignment.variables is not None: - if expose and (not assignment.exposed.value or - assignment.holdouts_pending) and \ - not self._expose(assignment) and \ - attempt < _MAX_EXPOSURE_ATTEMPTS: - # set_unit retired a candidate in between, so the key - # may resolve differently: walk it again. - return self._variable_value(key, default_value, expose, - attempt + 1) - - if key in assignment.variables and \ - (assignment.assigned or assignment.overridden or - assignment.rule_override): - return assignment.variables[key] - - if assignment.suppressed and not assignment.overridden and \ - not assignment.rule_override and \ - suppressed_fallback is None: - suppressed_fallback = assignment.variables - if suppressed_fallback is not None and key in suppressed_fallback: - return suppressed_fallback[key] - return default_value + # A refresh removed the indexed experiment after the index was + # read: neither its placeholder (id 0) nor a cached override of it + # may win. The identity check keeps warm reads lock-free. + if (assignment.id == 0 or self.index is not index) and \ + self.get_experiment(experiment.data.name) is None: + continue + if expose and assignment.holdout_assignments is not None and \ + not assignment.holdouts_exposed: + pending = pending or [] + pending.append(assignment) + if assignment.assigned or assignment.overridden or \ + assignment.rule_override: + winner = assignment + break + if assignment.suppressed and suppressed_fallback is None: + suppressed_fallback = assignment + else: + winner = suppressed_fallback + # A unit added during the walk may have retired a candidate it had + # already passed (a missing-unit loser that could now win), and a + # refresh may have removed one that still won from its cached + # override: either way the caller walks again. + invalidated = self._units_seq != units_seq or self.index is not index + if pending and not invalidated: + native = getattr(self.queue_exposure, "__func__", None) is \ + Context.queue_exposure + if native and winner is not None and \ + winner.holdout_assignments is not None: + # The winner's holdouts, and any arm a loser shares with it, + # are accepted with the winner (see _expose_winner), so a + # close a logger starts on a shared arm cannot publish it + # without the winner. A shared arm is therefore published in + # the winner's section (still before the winner's own + # exposure), after the losers' other arms: holdout order + # within a read is not guaranteed. + staged = {id(arm) for arm in winner.holdout_assignments + if arm is not None} + else: + staged = () + failure = None + for candidate in pending: + try: + self._expose_holdouts(candidate, offered, staged) + except Exception as error: + if failure is None: + failure = error + if staged and not candidate.holdouts_exposed: + deferred = deferred or [] + deferred.append(candidate) + if failure is not None: + raise failure + # A queue_exposure override may have added a unit while it was + # offered the holdouts. + invalidated = self._units_seq != units_seq or \ + self.index is not index + return winner, invalidated, deferred def peek_treatment(self, experiment_name: str): self.check_ready(True) @@ -1337,6 +1453,7 @@ def _rules_and_audience_match(self, experiment: Experiment, def get_assignment(self, experiment_name: str, exposed_at: int = None): checked_seq = None + fill = None try: self.context_lock.acquire_read() @@ -1352,12 +1469,27 @@ def get_assignment(self, experiment_name: str, exposed_at: int = None): pass elif experiment_name in self.overrides: override = self.overrides[experiment_name] + # Kept across refreshes, as in JS, so removing, restoring + # or re-identifying the experiment does not expose it + # again; only a placeholder (id 0) cached while the + # experiment was missing is recomputed once a refresh + # adds it. if assignment.overridden and \ assignment.variant == override and \ + (experiment is None or assignment.id != 0 or + experiment.data.id == 0) and \ (experiment is None or experiment.holdouts is assignment.holdouts or _holdout_set_matches(experiment, assignment)): - return assignment + if assignment.variables is None and \ + experiment is not None and \ + assignment.id == experiment.data.id and \ + 0 <= assignment.variant < \ + len(experiment.data.variants): + # Filled below, under the write lock. + fill = assignment + else: + return assignment elif experiment is None: if assignment.assigned is False and \ not assignment.rule_override: @@ -1379,6 +1511,27 @@ def get_assignment(self, experiment_name: str, exposed_at: int = None): finally: self.context_lock.release_read() + if fill is not None: + # A kept override without variables (cached before an id-0 + # experiment was known, or overridden to a variant it did not + # have yet) takes the variables of the same experiment, as JS + # followArm does. The experiment is read again and the variables + # stored under the write lock and data_lock together, so a + # reader that checked the cache before a refresh cannot store + # the replaced payload's variables. + try: + self.context_lock.acquire_write() + self.data_lock.acquire_read() + experiment = self.index.get(experiment_name, None) + if experiment is not None and \ + fill.id == experiment.data.id and \ + 0 <= fill.variant < len(experiment.data.variants): + fill.variables = experiment.variables[fill.variant] + return fill + finally: + self.data_lock.release_read() + self.context_lock.release_write() + if checked_seq is not None: # Attributes or the assignment rules changed since the assignment # was computed: re-check its rule and audience results under the @@ -1737,7 +1890,8 @@ def _retire(self, assignment: Assignment): finally: self.event_lock.release_write() - def _expose(self, assignment: Assignment): + def _expose(self, assignment: Assignment, offer_holdouts: bool = True, + holdouts_first: bool = False): """Expose an assignment; False when set_unit retired it first. JS _triggerExposures: a held-out experiment publishes no exposure of @@ -1747,13 +1901,31 @@ def _expose(self, assignment: Assignment): so a refresh in between cannot mix epochs. The whole group is accepted in one event_lock section, so a concurrent close either rejects all of it (and a later read retries) or publishes all of it; - the events are logged after the lock is released. + the events are logged after the lock is released. A variable read + passes holdouts_first=True so the holdouts precede the winner, as on + the walk; through a queue_exposure override it passes + offer_holdouts=False, since its walk already offered the holdouts + (_expose_holdouts) and a declined one is not offered twice in a read. """ if assignment.holdout_assignments is None: - return self.queue_exposure(assignment) is not False + if getattr(self.queue_exposure, "__func__", None) is \ + Context.queue_exposure: + return self.queue_exposure(assignment) is not False + # Like _expose_through_hook: an override is never handed an + # assignment set_unit already retired, and is judged by the + # state, since its return value (v0.2.4 hooks may return False + # to decline) is not a set_unit retirement. + try: + self.event_lock.acquire_write() + if assignment.retired: + return False + finally: + self.event_lock.release_write() + self.queue_exposure(assignment) + return assignment.exposed.value or not assignment.retired if getattr(self.queue_exposure, "__func__", None) is not \ Context.queue_exposure: - return self._expose_through_hook(assignment) + return self._expose_through_hook(assignment, offer_holdouts) accepted = [] try: @@ -1762,34 +1934,56 @@ def _expose(self, assignment: Assignment): if assignment.retired: return False exposed_at = assignment.exposedAt or self.clock.millis() - if assignment.suppressed and not assignment.overridden and \ - not assignment.rule_override: - assignment.exposed.compare_and_set(False, True) - else: - exposure = self._accept_exposure(assignment, assignment.name, - exposed_at) - if exposure is not None: - accepted.append(exposure) - for holdout, holdout_assignment in zip( - assignment.holdouts, assignment.holdout_assignments): - if holdout_assignment is not None: - # Named from this assignment's snapshot, like JS - # holdouts[i].data.name; the shared holdout assignment - # is not modified. + + def accept_assignment(): + if assignment.suppressed and not assignment.overridden and \ + not assignment.rule_override: + assignment.exposed.compare_and_set(False, True) + else: exposure = self._accept_exposure( - holdout_assignment, holdout.name, exposed_at) + assignment, assignment.name, exposed_at) if exposure is not None: accepted.append(exposure) + + if not holdouts_first: + accept_assignment() + if offer_holdouts: + self._accept_holdouts(assignment, exposed_at, accepted) + if holdouts_first: + accept_assignment() finally: self.event_lock.release_write() + if offer_holdouts: + assignment.holdouts_exposed = True + assignment.holdouts_pending = False + self._log_exposures(accepted) + return True + + def _accept_holdouts(self, assignment: Assignment, exposed_at, + accepted: list, staged=()): + # Under event_lock, after check_not_closed. Each exposure is named + # from this assignment's snapshot, like JS holdouts[i].data.name; + # the shared holdout assignment is not modified. Arms in `staged` + # are left for the winner's section. + for holdout, holdout_assignment in zip( + assignment.holdouts, assignment.holdout_assignments): + if holdout_assignment is not None and \ + id(holdout_assignment) not in staged: + exposure = self._accept_exposure( + holdout_assignment, holdout.name, exposed_at) + if exposure is not None: + accepted.append(exposure) + + def _log_exposures(self, accepted: list): + # After event_lock is released, so a logger may close or read. for exposure in accepted: self.log_event(EventType.EXPOSURE, exposure) if accepted: self.set_timeout() - return True - def _expose_through_hook(self, assignment: Assignment): + def _expose_through_hook(self, assignment: Assignment, + offer_holdouts: bool = True): # A subclass overriding queue_exposure (a v0.2.4 extension point) # keeps seeing every exposure, one call each, at the cost of the # grouped acceptance. The read's time is taken once for the group. @@ -1837,7 +2031,21 @@ def _expose_through_hook(self, assignment: Assignment): # retried. if not assignment.exposed.value and assignment.retired: return False + if not offer_holdouts: + if assignment.holdouts_exposed: + assignment.holdouts_pending = False + elif self._offer_holdouts_through_hook(assignment, exposed_at): + assignment.holdouts_pending = False + return True + + def _offer_holdouts_through_hook(self, assignment: Assignment, + exposed_at, offered=None): + # True when every holdout pinned on the assignment is exposed. A + # raising hook does not stop the other holdouts: the first error is + # raised after every one was offered (Java + # triggerApplicableHoldoutExposures). finished = True + failure = None for holdout, holdout_assignment in zip( assignment.holdouts, assignment.holdout_assignments): if holdout_assignment is None: @@ -1849,10 +2057,17 @@ def _expose_through_hook(self, assignment: Assignment): self.event_lock.acquire_write() if holdout_assignment.exposed.value: continue - if holdout_assignment.hook_pending: + if holdout_assignment.hook_pending or ( + offered is not None and + holdout_assignment in offered): finished = False continue holdout_assignment.hook_pending = True + if offered is not None: + # The arm itself, kept alive for the read: an id could be + # reused by an arm a refresh creates after this one is + # released. + offered.add(holdout_assignment) finally: self.event_lock.release_write() try: @@ -1863,13 +2078,63 @@ def _expose_through_hook(self, assignment: Assignment): view.name = holdout.name view.exposedAt = exposed_at self.queue_exposure(view) + except Exception as error: + if failure is None: + failure = error finally: holdout_assignment.hook_pending = False if not holdout_assignment.exposed.value: finished = False - if finished: + if failure is not None: + raise failure + return finished + + def _expose_holdouts(self, assignment: Assignment, offered=None, + staged=()): + """Expose the holdouts pinned on a variable-key candidate, not the + candidate itself (Java triggerApplicableHoldoutExposures). + + A held-out unit and a not held-out one fire the same holdouts on + every candidate visited, so both arms stay symmetric whichever + candidate wins the key. Unexposed ones are offered again on the next + read. + """ + if assignment.holdout_assignments is None or \ + assignment.holdouts_exposed: + return + if not self._holdouts_unexposed(assignment): + # The pinned arms never change and stay exposed. + assignment.holdouts_exposed = True assignment.holdouts_pending = False - return True + return + exposed_at = assignment.exposedAt or self.clock.millis() + if getattr(self.queue_exposure, "__func__", None) is not \ + Context.queue_exposure: + self._offer_holdouts_through_hook(assignment, exposed_at, + offered) + if not self._holdouts_unexposed(assignment): + assignment.holdouts_exposed = True + assignment.holdouts_pending = False + return + + accepted = [] + try: + self.event_lock.acquire_write() + self.check_not_closed() + self._accept_holdouts(assignment, exposed_at, accepted, staged) + finally: + self.event_lock.release_write() + + if not staged or not self._holdouts_unexposed(assignment): + assignment.holdouts_exposed = True + assignment.holdouts_pending = False + self._log_exposures(accepted) + + @staticmethod + def _holdouts_unexposed(assignment: Assignment): + return any(holdout_assignment is not None and + not holdout_assignment.exposed.value + for holdout_assignment in assignment.holdout_assignments) def _accept_exposure(self, assignment: Assignment, name, exposed_at): # Under event_lock, after check_not_closed: the exposure to queue, diff --git a/test/test_context.py b/test/test_context.py index b056073..0749407 100644 --- a/test/test_context.py +++ b/test/test_context.py @@ -744,7 +744,10 @@ def test_get_variable_strict(self): res = context.get_variable_value("banner.size", "small") self.assertEqual("small", res) - self.assertEqual(1, context.get_pending_count()) + # The strict audience mismatch leaves the only candidate unassigned, + # so nothing wins the key and nothing is exposed (Java + # getVariableValueDoesNotQueuesExposure...InStrictMode). + self.assertEqual(0, context.get_pending_count()) context.close() def test_get_variable_keys(self): @@ -1900,28 +1903,28 @@ def create_shared_key_context(self, experiments, units): return self.create_test_context(config, future) def test_variable_value_walks_shared_key_experiments_by_id(self): - # JS _variableValue: experiments sharing a key are visited in id - # order; the first one whose variables hold the key wins, and each - # visited experiment is exposed. Payload order must not matter. + # Java getVariableAssignment: experiments sharing a key are visited + # in id order and the first assigned one wins, even when its variant + # lacks the key (the default is returned). Only the winner is + # exposed. Payload order must not matter. self.set_up() exp_a = self.make_shared_key_experiment( 1, "exp_a", "user_id", None, "a_treatment") exp_b = self.make_shared_key_experiment( 2, "exp_b", "user_id", "b_control", "b_treatment") - fell_through = 0 + control = 0 for i in range(20): uid = f"uid-{i}" context = self.create_shared_key_context( [exp_b, exp_a], {"user_id": uid}) a = context.peek_treatment("exp_a") - b = context.peek_treatment("exp_b") if a == 1: - expected, exposed = "a_treatment", ["exp_a"] + expected = "a_treatment" else: - fell_through += 1 - expected = ["b_control", "b_treatment"][b] - exposed = ["exp_a", "exp_b"] + control += 1 + expected = "d" + exposed = ["exp_a"] self.assertEqual(expected, context.peek_variable_value("banner.size", "d")) @@ -1930,8 +1933,8 @@ def test_variable_value_walks_shared_key_experiments_by_id(self): context.get_variable_value("banner.size", "d")) self.assertEqual(exposed, [e.name for e in context.exposures]) context.close() - self.assertGreater(fell_through, 0) - self.assertLess(fell_through, 20) + self.assertGreater(control, 0) + self.assertLess(control, 20) def test_variable_value_skips_unassigned_experiment(self): self.set_up() @@ -1948,8 +1951,7 @@ def test_variable_value_skips_unassigned_experiment(self): self.assertEqual(expected, context.get_variable_value("banner.size", "d")) - self.assertEqual(["exp_a", "exp_b"], - [e.name for e in context.exposures]) + self.assertEqual(["exp_b"], [e.name for e in context.exposures]) context.set_override("exp_a", 1) self.assertEqual("a_treatment", @@ -2005,10 +2007,11 @@ def test_variable_value_override_on_unassigned_experiment_wins(self): self.assertEqual(["exp_a"], [e.name for e in context.exposures]) context.close() - def test_variable_value_assigned_variant_without_key_falls_through(self): - # (e) exp_a is overridden to a variant whose config lacks the key; - # `key in variables` is False, so the walk falls through to exp_b - # even though exp_a is assigned. Both experiments are exposed. + def test_variable_value_assigned_variant_without_key_returns_default(self): + # (e) exp_a is overridden to a variant whose config lacks the key. + # exp_a still wins the key, so the default is returned: falling + # through to exp_b would bias exp_b by exp_a's arm. Only exp_a is + # exposed. self.set_up() exp_a = self.make_shared_key_experiment_variants( 1, "exp_a", "user_id", @@ -2021,13 +2024,12 @@ def test_variable_value_assigned_variant_without_key_falls_through(self): # Override exp_a to the treatment variant, which does not define the # shared key. context.set_override("exp_a", 1) - expected = ["b_control", "b_treatment"][ - context.peek_treatment("exp_b")] - self.assertEqual(expected, + self.assertEqual("d", + context.peek_variable_value("banner.size", "d")) + self.assertEqual("d", context.get_variable_value("banner.size", "d")) - self.assertEqual(["exp_a", "exp_b"], - [e.name for e in context.exposures]) + self.assertEqual(["exp_a"], [e.name for e in context.exposures]) context.close() def test_set_override_allowed_after_close(self): diff --git a/test/test_context_holdouts.py b/test/test_context_holdouts.py index 86c972f..e2966a4 100644 --- a/test/test_context_holdouts.py +++ b/test/test_context_holdouts.py @@ -637,10 +637,10 @@ def get_assignment(name, exposed_at=None): context.get_variable_value("detached_var", "default")) self.assertEqual(2, context.get_pending_count()) self.assert_published( - context, self.exposure(1, "exp_winner", 1, unit="user_id", - full_on=True), + context, self.holdout_exposure(11, "holdout_detached_variable", 1, unit="user_id"), + self.exposure(1, "exp_winner", 1, unit="user_id", full_on=True), unit="user_id") def test_trigger_applicable_holdout_exposures_never_live_resolves_a_pinned_null_entry_for_an_already_exposed_assignment(self): @@ -1086,9 +1086,9 @@ def test_variable_value_on_held_out_rule_won_experiment(self): context.get_variable_value("color", "default")) self.assert_published( context, + self.holdout_exposure(11, "holdout_rules_suppression", 0), self.exposure(1, "exp_holdout_rules", 1, assigned=False, - rule_override=True), - self.holdout_exposure(11, "holdout_rules_suppression", 0)) + rule_override=True)) def test_shared_variable_key_prefers_rule_won_over_suppressed_experiment(self): context = self.create_context(context_data( diff --git a/test/test_holdout_contracts.py b/test/test_holdout_contracts.py index 0a3fe04..bf2aee9 100644 --- a/test/test_holdout_contracts.py +++ b/test/test_holdout_contracts.py @@ -303,8 +303,8 @@ def test_h8_shared_key_assigned_second_candidate_wins_and_both_holdouts_fire(sel context.get_variable_value("color", "default")) self.assertEqual( [self.holdout_exposure(11, "holdout_a", 0), - self.exposure(2, "exp_second", NORMAL_VARIANT), - self.holdout_exposure(12, "holdout_b", 1)], + self.holdout_exposure(12, "holdout_b", 1), + self.exposure(2, "exp_second", NORMAL_VARIANT)], self.exposure_tuples(context.exposures)) def test_223_exposure_state_survives_publish(self): @@ -512,9 +512,9 @@ def test_rule_beats_suppression_for_assign_and_split_and_variables(self): self.assertTrue(assignment.suppressed) self.assertTrue(assignment.rule_override) self.assertEqual( - [self.exposure(1, "exp_rule", 1, assigned=False, - rule_override=True), - self.holdout_exposure(11, "holdout_a", 0)], + [self.holdout_exposure(11, "holdout_a", 0), + self.exposure(1, "exp_rule", 1, assigned=False, + rule_override=True)], self.exposure_tuples(context.exposures)) def test_holdout_arm_uses_the_holdout_seeds_and_split(self): @@ -831,8 +831,9 @@ def counting(*args): class SuppressedFallbackTest(HoldoutTestCase): - """JS _resolveVariableValue: only a held-out candidate that neither an - override nor a rule decided becomes the control-value fallback.""" + """Only a held-out candidate that neither an override nor a rule decided + becomes the control-value fallback: an overridden or rule-won one wins + the key, even when its variant lacks it (Java getVariableAssignment).""" def two_candidates(self, first_fields=None, overrides=None): first = self.covered(1, "exp_first", [11], **(first_fields or {})) @@ -845,19 +846,29 @@ def two_candidates(self, first_fields=None, overrides=None): def test_overridden_held_out_candidate_is_not_the_fallback(self): context = self.two_candidates(overrides={"exp_first": 0}) - self.assertEqual("control", + self.assertEqual("default", context.peek_variable_value("color", "default")) - self.assertEqual("control", + self.assertEqual("default", context.get_variable_value("color", "default")) + self.assertEqual( + [self.holdout_exposure(11, "holdout_a", 0), + self.exposure(1, "exp_first", 0, assigned=False, + overridden=True)], + self.exposure_tuples(context.exposures)) def test_rule_won_held_out_candidate_is_not_the_fallback(self): rule = json.dumps({"rules": [{"type": "assign", "variant": 0}]}) context = self.two_candidates({"assignmentRules": rule}) self.assertTrue(context.get_assignment("exp_first").rule_override) - self.assertEqual("control", + self.assertEqual("default", context.peek_variable_value("color", "default")) - self.assertEqual("control", + self.assertEqual("default", context.get_variable_value("color", "default")) + self.assertEqual( + [self.holdout_exposure(11, "holdout_a", 0), + self.exposure(1, "exp_first", 0, assigned=False, + rule_override=True)], + self.exposure_tuples(context.exposures)) def test_held_out_assignment_rechecks_the_audience_once_like_js(self): # JS audienceMatches runs for a held-out assignment too; a changed @@ -1329,20 +1340,23 @@ class Delegating(Context): def queue_exposure(self, assignment): return super().queue_exposure(assignment) + # The candidate's holdouts are offered before its own exposure, so + # closing on the first one leaves the second and the experiment. context = self.create_context(context_data( - [with_variables(self.covered(1, "exp", [11]), "color")], - [self.holdout_b(id=11, name="h")])) + [with_variables(self.covered(1, "exp", [11, 12]), "color")], + [self.holdout_b(id=11, name="h"), + self.holdout_b(id=12, name="h2")])) context.__class__ = Delegating failing = Future() self.client.publish_results.append(failing) closing = [] - def close_on_own_exposure(event_type, data): - if event_type == EventType.EXPOSURE and data.id == 1 and \ + def close_on_first_holdout(event_type, data): + if event_type == EventType.EXPOSURE and data.id == 11 and \ not closing: closing.append(context.close_async()) - self.logger.on_event = close_on_own_exposure + self.logger.on_event = close_on_first_holdout with self.assertRaises(ContextError): context.get_variable_value("color", "default") self.logger.on_event = None @@ -1351,7 +1365,8 @@ def close_on_own_exposure(event_type, data): closing[0].result(5) self.assertEqual("treatment", context.get_variable_value("color", "default")) - self.assertEqual(["exp", "h"], [e.name for e in context.exposures]) + self.assertEqual(["h", "h2", "exp"], + [e.name for e in context.exposures]) def test_hook_path_stops_revisiting_once_holdouts_are_finished(self): from sdk.context import Context diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py new file mode 100644 index 0000000..deb0109 --- /dev/null +++ b/test/test_shared_variable_keys.py @@ -0,0 +1,1321 @@ +"""Shared variable keys (Java core-api Context.getVariableAssignment): the +candidates are the experiments whose variants define the key, in id order; +the first one the unit is assigned to, overridden in or rule-assigned to +wins, and only the winner is exposed.""" +import json +import unittest + +from sdk.context_event_logger import EventType +from test.holdout_fixtures import ( + HOLDOUT_A_SEEDS, HOLDOUT_B_SEEDS, NORMAL_VARIANT, UID, UID_NOT_HELD_OUT, + UNIT_TYPE, HoldoutFixture, context_data, experiment, holdout, + with_variables) + +KEY = "banner.size" +GOLD_ONLY = json.dumps( + {"filter": [{"eq": [{"var": "tier"}, {"value": "gold"}]}]}) +ASSIGN_CONTROL = json.dumps({"rules": [{"type": "assign", "variant": 0}]}) + + +def strict_mismatch(id, name, **fields): + # No "tier" attribute is set, so the strict audience never matches. + return with_variables( + experiment(id, name, audience=GOLD_ONLY, audienceStrict=True, + **fields), KEY, f"{name}_control", f"{name}_treatment") + + +def missing_unit(id, name, **fields): + return with_variables(experiment(id, name, unit_type="device_id", + **fields), + KEY, f"{name}_control", f"{name}_treatment") + + +def assigned(id, name, **fields): + return with_variables(experiment(id, name, **fields), + KEY, f"{name}_control", f"{name}_treatment") + + +def configs(id, name, *variant_variables, **fields): + data = experiment(id, name, **fields) + data["variants"] = [ + {"name": f"v{i}", + "config": None if variables is None else json.dumps(variables)} + for i, variables in enumerate(variant_variables)] + return data + + +class SharedVariableKeyTest(HoldoutFixture, unittest.TestCase): + def setUp(self): + self.set_up_fixture() + + def names(self, context): + return [e.name for e in context.exposures] + + def assert_winner(self, experiments, expected, exposed, holdouts=None, + **kwargs): + context = self.create_context(context_data(experiments, holdouts), + **kwargs) + self.assertEqual(expected, context.peek_variable_value(KEY, "d")) + self.assertEqual(0, context.get_pending_count()) + self.assertEqual(expected, context.get_variable_value(KEY, "d")) + self.assertEqual(exposed, self.names(context)) + self.assertEqual(len(exposed), context.get_pending_count()) + self.assertEqual(expected, context.get_variable_value(KEY, "d")) + self.assertEqual(exposed, self.names(context)) + return context + + def test_lower_id_strict_audience_mismatch_is_not_exposed(self): + for order in (1, -1): + with self.subTest(order=order): + self.assert_winner( + [strict_mismatch(1, "exp_a"), + assigned(2, "exp_b")][::order], + "exp_b_treatment", ["exp_b"]) + + def test_lower_id_without_its_unit_is_not_exposed(self): + for order in (1, -1): + with self.subTest(order=order): + self.assert_winner( + [missing_unit(1, "exp_a"), assigned(2, "exp_b")][::order], + "exp_b_treatment", ["exp_b"]) + + def test_only_candidate_the_unit_is_not_in_is_not_exposed(self): + # 0.3.0 exposed it; nothing wins the key now, as in Java. + for only in (strict_mismatch(1, "exp_a"), missing_unit(1, "exp_a")): + with self.subTest(unit_type=only["unitType"]): + context = self.assert_winner([only], "d", []) + context.get_treatment("exp_a") + self.assertEqual(["exp_a"], self.names(context)) + + def test_winner_exposure_is_the_winning_assignment(self): + context = self.assert_winner( + [strict_mismatch(1, "exp_a"), missing_unit(2, "exp_b"), + assigned(3, "exp_c")], + "exp_c_treatment", ["exp_c"]) + self.assertEqual([self.exposure(3, "exp_c", NORMAL_VARIANT)], + self.exposure_tuples(context.exposures)) + + def test_winner_variant_without_the_key_returns_default(self): + # exp_a wins with variant 1, which lacks the key: exp_b, holdout + # included, is never consulted. + context = self.assert_winner( + [configs(1, "exp_a", {KEY: "a0"}, {"other": "x"}), + assigned(2, "exp_b", holdout_ids=[12])], + "d", ["exp_a"], + holdouts=[holdout(12, "holdout_b", HOLDOUT_B_SEEDS)]) + self.assertEqual([], [e.name for e in context.exposures + if e.name == "holdout_b"]) + + def test_winner_variant_without_any_config_returns_default(self): + self.assert_winner( + [configs(1, "exp_a", {KEY: "a0"}, None), assigned(2, "exp_b")], + "d", ["exp_a"]) + + def test_overridden_winner_variant_without_the_key_returns_default(self): + context = self.assert_winner( + [configs(1, "exp_a", {KEY: "a0"}, {"other": "x"}), + assigned(2, "exp_b")], + "d", ["exp_a"], overrides={"exp_a": 1}) + self.assertTrue(context.exposures[0].overridden) + + def test_no_candidate_assigned_returns_default_and_exposes_nothing(self): + self.assert_winner( + [strict_mismatch(1, "exp_a"), missing_unit(2, "exp_b")], + "d", []) + + def test_peek_exposes_nothing(self): + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a"), assigned(2, "exp_b")])) + for _ in range(2): + self.assertEqual("exp_b_treatment", + context.peek_variable_value(KEY, "d")) + self.assertEqual(0, context.get_pending_count()) + self.assertEqual([], self.names(context)) + + def test_peek_never_falls_through_past_the_winner(self): + context = self.create_context(context_data( + [missing_unit(1, "exp_a"), + configs(2, "exp_b", {KEY: "b0"}, {"other": "x"}), + assigned(3, "exp_c")])) + self.assertEqual("d", context.peek_variable_value(KEY, "d")) + self.assertEqual(0, context.get_pending_count()) + + def test_override_on_a_candidate_without_its_unit_wins(self): + context = self.assert_winner( + [strict_mismatch(1, "exp_a"), missing_unit(2, "exp_b"), + assigned(3, "exp_c")], + "exp_b_control", ["exp_b"], overrides={"exp_b": 0}) + self.assertTrue(context.exposures[0].overridden) + + def test_override_beats_the_assigned_variant(self): + self.assert_winner( + [missing_unit(1, "exp_a"), assigned(2, "exp_b"), + assigned(3, "exp_c")], + "exp_b_control", ["exp_b"], overrides={"exp_b": 0}) + + def test_override_on_a_higher_id_loses_to_an_assigned_lower_id(self): + self.assert_winner( + [missing_unit(1, "exp_a"), assigned(2, "exp_b"), + assigned(3, "exp_c")], + "exp_b_treatment", ["exp_b"], overrides={"exp_c": 0}) + + def test_override_on_a_higher_id_wins_over_an_unassigned_lower_id(self): + self.assert_winner( + [strict_mismatch(1, "exp_a"), missing_unit(2, "exp_b")], + "exp_b_control", ["exp_b"], overrides={"exp_b": 0}) + + def test_rule_on_a_candidate_without_its_unit_wins(self): + context = self.assert_winner( + [strict_mismatch(1, "exp_a"), + missing_unit(2, "exp_b", assignmentRules=ASSIGN_CONTROL), + assigned(3, "exp_c")], + "exp_b_control", ["exp_b"]) + self.assertTrue(context.exposures[0].ruleOverride) + + def test_rule_beats_a_strict_audience_mismatch(self): + context = self.assert_winner( + [missing_unit(1, "exp_a"), + strict_mismatch(2, "exp_b", assignmentRules=ASSIGN_CONTROL), + assigned(3, "exp_c")], + "exp_b_control", ["exp_b"]) + self.assertTrue(context.exposures[0].ruleOverride) + + def test_rule_on_a_higher_id_loses_to_an_assigned_lower_id(self): + self.assert_winner( + [missing_unit(1, "exp_a"), assigned(2, "exp_b"), + assigned(3, "exp_c", assignmentRules=ASSIGN_CONTROL)], + "exp_b_treatment", ["exp_b"]) + + def test_falsy_values_are_returned_and_a_missing_key_is_the_default(self): + cases = [(None, None), (False, False), (0, 0), (0.0, 0.0), ("", ""), + ({}, {}), ([], [])] + for value, expected in cases: + with self.subTest(value=value): + self.setUp() + context = self.assert_winner( + [missing_unit(1, "exp_a"), + configs(2, "exp_b", {KEY: "b0"}, {KEY: value}), + assigned(3, "exp_c")], + expected, ["exp_b"]) + self.assertIs(type(expected), + type(context.get_variable_value(KEY, "d"))) + with self.subTest(value="missing"): + self.setUp() + self.assert_winner( + [missing_unit(1, "exp_a"), + configs(2, "exp_b", {KEY: "b0"}, {}), + assigned(3, "exp_c")], + "d", ["exp_b"]) + + def test_not_eligible_winner_is_exposed_with_control(self): + # Outside traffic is still assigned (variant 0): it wins the key. + context = self.assert_winner( + [missing_unit(1, "exp_a"), + assigned(2, "exp_b", trafficSplit=[1.0, 0.0]), + assigned(3, "exp_c")], + "exp_b_control", ["exp_b"]) + self.assertFalse(context.exposures[0].eligible) + + def test_losing_candidate_fires_only_its_holdouts(self): + # Java fires the applicable holdouts of every candidate visited on + # the non-peek path; the candidate's own exposure is never queued. + loser = strict_mismatch(1, "exp_a", holdout_ids=[12]) + context = self.create_context(context_data( + [loser, assigned(2, "exp_b")], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)])) + self.assertEqual("exp_b_treatment", + context.peek_variable_value(KEY, "d")) + self.assertEqual(0, context.get_pending_count()) + self.assertEqual("exp_b_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual( + [self.holdout_exposure(12, "holdout_b", 1), + self.exposure(2, "exp_b", NORMAL_VARIANT)], + self.exposure_tuples(context.exposures)) + self.assertFalse(context.get_assignment("exp_a").exposed.value) + + def test_losing_candidate_holdouts_go_through_a_queue_exposure_hook(self): + from sdk.context import Context + offered = [] + + class Recording(Context): + def queue_exposure(self, assignment): + offered.append(assignment.name) + return super().queue_exposure(assignment) + + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a", holdout_ids=[12]), + assigned(2, "exp_b")], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)])) + context.__class__ = Recording + self.assertEqual("exp_b_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual(["holdout_b", "exp_b"], offered) + self.assertEqual(["holdout_b", "exp_b"], self.names(context)) + self.assertEqual("exp_b_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual(["holdout_b", "exp_b"], offered) + + def test_losing_candidate_holdouts_are_not_queued_while_closing(self): + from sdk.context_error import ContextError + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a", holdout_ids=[12]), + assigned(2, "exp_b")], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)])) + # Closing starts after the read's readiness check, while the + # candidates are being resolved. + get_assignment = context.get_assignment + context.get_assignment = \ + lambda name: context.closing.set(True) or get_assignment(name) + with self.assertRaises(ContextError): + context.get_variable_value(KEY, "d") + self.assertEqual([], self.names(context)) + self.assertEqual(0, context.get_pending_count()) + self.assertFalse( + context._holdout_assignments[(12, UNIT_TYPE)].exposed.value) + # A failed close reopens the context: the next read still queues + # the holdout the closing read could not. + context.get_assignment = get_assignment + context.closing.set(False) + self.assertFalse(context.get_assignment("exp_a").holdouts_exposed) + self.assertEqual("exp_b_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual(["holdout_b", "exp_b"], self.names(context)) + + def test_losing_candidate_holdout_is_named_from_its_snapshot(self): + # The arm is cached under the old name; a same-iteration rename + # keeps it, and the exposure carries the payload's current name. + context = self.create_context(context_data( + [assigned(3, "exp_c", holdout_ids=[12])], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)])) + context.peek_treatment("exp_c") + self.refresh(context, context_data( + [strict_mismatch(1, "exp_a", holdout_ids=[12]), + assigned(2, "exp_b")], + [holdout(12, "renamed", HOLDOUT_B_SEEDS)])) + self.assertEqual("exp_b_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual(["renamed", "exp_b"], self.names(context)) + + def test_warm_read_takes_no_event_lock(self): + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a", holdout_ids=[12]), + assigned(2, "exp_b", holdout_ids=[12])], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)])) + context.get_variable_value(KEY, "d") + for name in ("exp_a", "exp_b"): + self.assertTrue(context.get_assignment(name).holdouts_exposed) + calls = [] + acquire = context.event_lock.acquire_write + context.event_lock.acquire_write = \ + lambda: calls.append(1) or acquire() + scans = [] + context._holdouts_unexposed = \ + lambda assignment: scans.append(1) or True + self.assertEqual("exp_b_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual([], calls) + self.assertEqual([], scans) + + def test_holdouts_exposed_by_a_treatment_take_no_event_lock(self): + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a", holdout_ids=[12]), + assigned(2, "exp_b"), assigned(3, "exp_c", holdout_ids=[12])], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)])) + context.get_treatment("exp_c") + context.get_treatment("exp_b") + calls = [] + acquire = context.event_lock.acquire_write + context.event_lock.acquire_write = \ + lambda: calls.append(1) or acquire() + self.assertEqual("exp_b_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual([], calls) + self.assertTrue(context.get_assignment("exp_a").holdouts_exposed) + + def test_hook_winner_holdouts_leave_nothing_pending(self): + # Through a queue_exposure override, a variable read that exposes + # the winner and its holdouts leaves no holdout pending, so later + # treatment reads take no event lock. + from sdk.context import Context + + class PassThrough(Context): + def queue_exposure(self, assignment): + return super().queue_exposure(assignment) + + context = self.create_context(context_data( + [assigned(1, "exp_a", holdout_ids=[12])], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)])) + context.__class__ = PassThrough + context.get_variable_value(KEY, "d") + self.assertEqual(["holdout_b", "exp_a"], self.names(context)) + self.assertFalse(context.get_assignment("exp_a").holdouts_pending) + calls = [] + acquire = context.event_lock.acquire_write + context.event_lock.acquire_write = \ + lambda: calls.append(1) or acquire() + for _ in range(3): + context.get_treatment("exp_a") + self.assertEqual([], calls) + + def test_losing_candidate_holdouts_use_its_exposure_time(self): + # Like Context._expose: a candidate resolved with an exposure time + # (get_treatment(name, exposed_at)) stamps its holdouts with it. + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a", holdout_ids=[12]), + assigned(2, "exp_b")], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)])) + context.get_assignment("exp_a").exposedAt = 123 + context.get_variable_value(KEY, "d") + self.assertEqual([("holdout_b", 123), ("exp_b", self.clock.millis())], + [(e.name, e.exposedAt) for e in context.exposures]) + + def test_holdout_a_hook_declines_is_offered_again(self): + from sdk.context import Context + declined = [] + + class Declining(Context): + def queue_exposure(self, assignment): + if assignment.name == "holdout_b" and not declined: + declined.append(1) + return None + return super().queue_exposure(assignment) + + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a", holdout_ids=[12]), + assigned(2, "exp_b")], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)])) + context.__class__ = Declining + context.get_variable_value(KEY, "d") + self.assertEqual(["exp_b"], self.names(context)) + self.assertFalse(context.get_assignment("exp_a").holdouts_exposed) + context.get_variable_value(KEY, "d") + self.assertEqual(["exp_b", "holdout_b"], self.names(context)) + self.assertTrue(context.get_assignment("exp_a").holdouts_exposed) + + def test_winner_holdout_a_hook_declines_is_offered_once_per_read(self): + # The walk offers the winner's holdouts; queuing the winner's own + # exposure must not offer a declined one again in the same read. + from sdk.context import Context + offered = [] + + class Declining(Context): + def queue_exposure(self, assignment): + offered.append(assignment.name) + if assignment.name == "holdout_b" and \ + offered.count("holdout_b") == 1: + return None + return super().queue_exposure(assignment) + + context = self.create_context(context_data( + [assigned(1, "exp_a", holdout_ids=[12])], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)])) + context.__class__ = Declining + self.assertEqual("exp_a_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual(["holdout_b", "exp_a"], offered) + self.assertEqual(["exp_a"], self.names(context)) + self.assertTrue(context.get_assignment("exp_a").holdouts_pending) + context.get_variable_value(KEY, "d") + self.assertEqual(["holdout_b", "exp_a", "holdout_b"], offered) + self.assertEqual(["exp_a", "holdout_b"], self.names(context)) + self.assertFalse(context.get_assignment("exp_a").holdouts_pending) + context.get_variable_value(KEY, "d") + self.assertEqual(3, len(offered)) + + def test_raising_hook_does_not_stop_the_other_holdouts(self): + # Java collects the first failure, fires every visited candidate's + # holdouts and rethrows before the winner is exposed. + from sdk.context import Context + + offered = [] + + class Raising(Context): + def queue_exposure(self, assignment): + offered.append(assignment.name) + if assignment.name in ("h1", "h2") and \ + not assignment.exposed.value: + raise RuntimeError(assignment.name + " failed") + return super().queue_exposure(assignment) + + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a", holdout_ids=[11, 12]), + strict_mismatch(2, "exp_b", holdout_ids=[13]), + assigned(3, "exp_c")], + [holdout(11, "h1", HOLDOUT_B_SEEDS), + holdout(12, "h2", HOLDOUT_B_SEEDS), + holdout(13, "h3", HOLDOUT_B_SEEDS)])) + context.__class__ = Raising + with self.assertRaisesRegex(RuntimeError, "h1 failed"): + context.get_variable_value(KEY, "d") + self.assertEqual(["h1", "h2", "h3"], offered) + self.assertEqual(["h3"], self.names(context)) + + def test_losing_candidate_holdout_exposure_is_logged(self): + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a", holdout_ids=[12]), + assigned(2, "exp_b")], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)])) + context.get_variable_value(KEY, "d") + self.assertEqual(["holdout_b", "exp_b"], + [e.name for e in self.exposure_events()]) + + def test_override_to_a_missing_variant_still_wins(self): + # Java: an overridden candidate wins even when the override names a + # variant the experiment does not have; it has no variables, so the + # default is returned and only it is exposed. + context = self.assert_winner( + [assigned(1, "exp_a"), assigned(2, "exp_b")], + "d", ["exp_a"], overrides={"exp_a": 5}) + self.assertEqual( + [self.exposure(1, "exp_a", 5, assigned=False, overridden=True)], + self.exposure_tuples(context.exposures)) + + def test_unit_type_of_exposure(self): + context = self.assert_winner( + [missing_unit(1, "exp_a"), assigned(2, "exp_b")], + "exp_b_treatment", ["exp_b"]) + self.assertEqual(UNIT_TYPE, context.exposures[0].unit) + + def test_no_winner_still_fires_the_holdouts_of_both_arms(self): + # Java fires the holdouts of every visited candidate even when none + # wins, so held-out and not held-out units both publish the holdout. + # The held-out unit gets the suppressed fallback's control value. + for uid, arm, value in ((UID, 0, "exp_a_control"), + (UID_NOT_HELD_OUT, 1, "d")): + with self.subTest(arm=arm): + self.setUp() + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a", holdout_ids=[11])], + [holdout(11, "holdout_a", HOLDOUT_A_SEEDS)]), + units={UNIT_TYPE: uid}) + self.assertEqual(value, + context.get_variable_value(KEY, "d")) + self.assertEqual( + [self.holdout_exposure(11, "holdout_a", arm)], + self.exposure_tuples(context.exposures)) + + def test_warm_read_without_holdouts_skips_the_holdout_pass(self): + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a"), assigned(2, "exp_b")])) + context.get_variable_value(KEY, "d") + calls = [] + context._expose_holdouts = lambda assignment: calls.append(1) + self.assertEqual("exp_b_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual([], calls) + + def test_set_unit_during_the_walk_walks_the_key_again(self): + # Both candidates' units are missing when the read starts. set_unit + # retires exp_a after the walk resolved it, so exp_b is never the + # first eligible candidate: the read walks again and exp_a wins. + context = self.create_context(context_data( + [missing_unit(1, "exp_a"), + assigned(2, "exp_b", unit_type="user_id")]), units={}) + get_assignment = context.get_assignment + resolved = [] + + def set_units_after_exp_a(name, exposed_at=None): + assignment = get_assignment(name, exposed_at=exposed_at) + resolved.append(name) + if resolved == ["exp_a"]: + context.set_unit("device_id", UID) + context.set_unit("user_id", UID) + return assignment + + context.get_assignment = set_units_after_exp_a + self.assertEqual("exp_a_treatment", + context.get_variable_value(KEY, "d")) + context.get_assignment = get_assignment + self.assertEqual(["exp_a"], self.names(context)) + self.assertEqual("exp_a_treatment", + context.peek_variable_value(KEY, "d")) + + def test_set_unit_after_a_candidate_was_checked_walks_the_key_again(self): + # The units arrive after exp_a was checked (and not retired at that + # point) but before exp_b is looked up: exp_b would win a key exp_a + # now wins, so the read walks again instead of exposing exp_b. + context = self.create_context(context_data( + [missing_unit(1, "exp_a"), + assigned(2, "exp_b", unit_type="user_id")]), units={}) + get_assignment = context.get_assignment + + def set_units_before_exp_b(name, exposed_at=None): + if name == "exp_b" and context.get_unit("user_id") is None: + context.set_unit("device_id", UID) + context.set_unit("user_id", UID) + return get_assignment(name, exposed_at=exposed_at) + + context.get_assignment = set_units_before_exp_b + self.assertEqual("exp_a_treatment", + context.get_variable_value(KEY, "d")) + context.get_assignment = get_assignment + self.assertEqual("exp_a_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual(["exp_a"], self.names(context)) + + def test_set_unit_with_a_unit_already_set_does_not_walk_again(self): + # Only a newly added unit retires assignments; setting the same UID + # again during the walk must not make the read walk a second time. + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a"), assigned(2, "exp_b")])) + get_assignment = context.get_assignment + resolved = [] + + def set_same_unit(name, exposed_at=None): + resolved.append(name) + context.set_unit(UNIT_TYPE, UID) + return get_assignment(name, exposed_at=exposed_at) + + context.get_assignment = set_same_unit + self.assertEqual("exp_b_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual(["exp_a", "exp_b"], resolved) + + def test_peek_walks_the_key_again_when_a_unit_arrives(self): + context = self.create_context(context_data( + [missing_unit(1, "exp_a"), + assigned(2, "exp_b", unit_type="user_id")]), units={}) + get_assignment = context.get_assignment + + def set_units_before_exp_b(name, exposed_at=None): + if name == "exp_b" and context.get_unit("user_id") is None: + context.set_unit("device_id", UID) + context.set_unit("user_id", UID) + return get_assignment(name, exposed_at=exposed_at) + + context.get_assignment = set_units_before_exp_b + self.assertEqual("exp_a_treatment", + context.peek_variable_value(KEY, "d")) + self.assertEqual(0, context.get_pending_count()) + + def test_invalidated_walk_offers_no_holdouts_before_walking_again(self): + # The stale walk passes exp_m, a loser with a holdout; the retry + # stops at exp_a and never visits exp_m, so its holdout never fires. + context = self.create_context(context_data( + [missing_unit(1, "exp_a"), + strict_mismatch(2, "exp_m", holdout_ids=[12]), + assigned(3, "exp_b", unit_type="user_id")], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)]), + units={UNIT_TYPE: UID, "user_id": UID}) + get_assignment = context.get_assignment + + def set_unit_before_exp_b(name, exposed_at=None): + if name == "exp_b" and context.get_unit("device_id") is None: + context.set_unit("device_id", UID) + return get_assignment(name, exposed_at=exposed_at) + + context.get_assignment = set_unit_before_exp_b + self.assertEqual("exp_a_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual(["exp_a"], self.names(context)) + + def test_unit_added_by_a_hook_during_the_holdout_pass_walks_again(self): + # The override adds exp_a's unit while it is offered exp_b's + # holdout; exp_b (user_id) is not retired, so only re-checking after + # the holdout pass makes the read return and expose exp_a. + from sdk.context import Context + + class SettingUnit(Context): + def queue_exposure(self, assignment): + if assignment.name == "holdout_b" and \ + self.get_unit("device_id") is None: + self.set_unit("device_id", UID) + return super().queue_exposure(assignment) + + context = self.create_context(context_data( + [missing_unit(1, "exp_a"), + assigned(2, "exp_b", unit_type="user_id", holdout_ids=[12])], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS, unit_type="user_id")]), + units={"user_id": UID}) + context.__class__ = SettingUnit + self.assertEqual("exp_a_treatment", + context.get_variable_value(KEY, "d")) + self.assertNotIn("exp_b", self.names(context)) + self.assertIn("exp_a", self.names(context)) + + def test_cached_override_of_an_experiment_a_refresh_removed_cannot_win( + self): + # exp_a's override is cached with its real id; the refresh lands + # after the walk read the index, so the cache alone would let it win. + context = self.create_context(context_data( + [assigned(1, "exp_a"), assigned(2, "exp_b")]), + overrides={"exp_a": 1}) + context.get_assignment("exp_a") + get_assignment = context.get_assignment + refreshed = [] + + def refresh_first(name, exposed_at=None): + if not refreshed: + refreshed.append(name) + self.refresh(context, context_data([assigned(2, "exp_b")])) + return get_assignment(name, exposed_at=exposed_at) + + context.get_assignment = refresh_first + for read in (context.peek_variable_value, + context.get_variable_value): + refreshed.clear() + self.refresh(context, context_data( + [assigned(1, "exp_a"), assigned(2, "exp_b")])) + context.get_assignment = get_assignment + context.get_assignment("exp_a") + context.get_assignment = refresh_first + with self.subTest(read=read.__name__): + self.assertEqual("exp_b_treatment", read(KEY, "d")) + context.get_assignment = get_assignment + self.assertEqual([self.exposure(2, "exp_b", NORMAL_VARIANT)], + self.exposure_tuples(context.exposures)) + + def test_experiment_a_refresh_adds_during_the_walk_wins(self): + # The walk read the old index (only exp_b); the refresh adds the + # overridden, lower-id exp_a, which wins the key in the new data. + for read in ("peek_variable_value", "get_variable_value"): + with self.subTest(read=read): + self.setUp() + context = self.create_context( + context_data([assigned(2, "exp_b")]), + overrides={"exp_a": 1}) + get_assignment = context.get_assignment + refreshed = [] + + def refresh_first(name, exposed_at=None): + if not refreshed: + refreshed.append(name) + self.refresh(context, context_data( + [assigned(1, "exp_a"), assigned(2, "exp_b")])) + return get_assignment(name, exposed_at=exposed_at) + + context.get_assignment = refresh_first + self.assertEqual("exp_a_treatment", + getattr(context, read)(KEY, "d")) + self.assertNotIn("exp_b", self.names(context)) + + def test_read_that_never_sees_one_state_returns_the_default(self): + # Every walk sees exp_a removed right after its cached override was + # resolved and restored by the time it reaches exp_m. No attempt + # sees one coherent state, so the read returns the default and + # exposes nothing, holdouts included, rather than a winner neither + # payload would give on its own. + holdouts = [holdout(13, "holdout_m", HOLDOUT_B_SEEDS)] + others = [strict_mismatch(2, "exp_m", holdout_ids=[13]), + assigned(3, "exp_b")] + full = context_data([assigned(1, "exp_a")] + others, holdouts) + context = self.create_context(full, overrides={"exp_a": 1}) + context.get_assignment("exp_a") + get_assignment = context.get_assignment + + def flip(name, exposed_at=None): + if name == "exp_a": + assignment = get_assignment(name, exposed_at=exposed_at) + self.refresh(context, context_data(others, holdouts)) + return assignment + if name == "exp_m": + self.refresh(context, full) + return get_assignment(name, exposed_at=exposed_at) + + context.get_assignment = flip + self.assertEqual("d", context.get_variable_value(KEY, "d")) + self.assertEqual([], self.names(context)) + context.get_assignment = get_assignment + self.assertEqual("exp_a_treatment", + context.get_variable_value(KEY, "d")) + + def test_override_placeholder_cached_before_a_refresh_adds_the_experiment( + self): + # peek_treatment caches exp_a's override while exp_a is missing (id + # 0); once a refresh adds it, the read must resolve it again and win + # with its real id, not return the default with an id-0 exposure. + context = self.create_context(context_data([assigned(2, "exp_b")]), + overrides={"exp_a": 1}) + context.peek_treatment("exp_a") + self.refresh(context, context_data( + [assigned(1, "exp_a"), assigned(2, "exp_b")])) + self.assertEqual("exp_a_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual( + [self.exposure(1, "exp_a", 1, assigned=False, overridden=True)], + self.exposure_tuples(context.exposures)) + + def test_warm_shared_key_read_takes_no_data_lookup(self): + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a"), assigned(2, "exp_b")])) + context.get_variable_value(KEY, "d") + calls = [] + get_experiment = context.get_experiment + context.get_experiment = \ + lambda name: calls.append(name) or get_experiment(name) + for _ in range(3): + self.assertEqual("exp_b_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual([], calls) + + def test_refresh_by_a_hook_during_the_holdout_pass_walks_again(self): + # The override refreshes in a lower-id overridden exp_a while it is + # offered exp_b's holdout; only re-checking the index after the + # holdout pass makes the read return and expose exp_a. + from sdk.context import Context + fixture = self + holdouts = [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)] + + class Refreshing(Context): + def queue_exposure(self, assignment): + if assignment.name == "holdout_b" and \ + self.get_experiment("exp_a") is None: + fixture.refresh(self, context_data( + [assigned(1, "exp_a"), + assigned(2, "exp_b", holdout_ids=[12])], holdouts)) + return super().queue_exposure(assignment) + + context = self.create_context(context_data( + [assigned(2, "exp_b", holdout_ids=[12])], holdouts), + overrides={"exp_a": 1}) + context.__class__ = Refreshing + self.assertEqual("exp_a_treatment", + context.get_variable_value(KEY, "d")) + self.assertNotIn("exp_b", self.names(context)) + + def test_index_is_read_under_the_data_lock(self): + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a"), assigned(2, "exp_b")])) + lock = context.data_lock + held = [] + acquire, release = lock.acquire_write, lock.release_write + state = {"in": False} + + def acquire_write(): + acquire() + state["in"] = True + + def release_write(): + state["in"] = False + release() + + class Index(dict): + def get(self, key, default=None): + held.append(state["in"]) + return dict.get(self, key, default) + + lock.acquire_write, lock.release_write = acquire_write, release_write + context.index_variables = Index(context.index_variables) + context.get_variable_value(KEY, "d") + self.assertEqual([True], held) + # The index the walk compares against is read under the lock too: a + # refresh between the two reads must make the read walk again. + index_reads = [] + cls = type(context) + + class Watching(cls): + @property + def index(self): + index_reads.append(state["in"]) + return self.__dict__["index"] + + @index.setter + def index(self, value): + self.__dict__["index"] = value + + context.__class__ = Watching + context.get_variable_value(KEY, "d") + self.assertTrue(index_reads) + self.assertTrue(index_reads[0]) + + def test_exposed_override_is_not_exposed_again_after_its_removal(self): + # As on 0.3.0 and in JS: the cached override survives a refresh that + # removes its experiment, so get_treatment does not expose it twice. + context = self.create_context(context_data( + [assigned(1, "exp_a"), assigned(2, "exp_b")]), + overrides={"exp_a": 1}) + self.assertEqual(1, context.get_treatment("exp_a")) + for _ in range(3): + self.refresh(context, context_data([assigned(2, "exp_b")])) + self.assertEqual(1, context.get_treatment("exp_a")) + self.refresh(context, context_data( + [assigned(1, "exp_a"), assigned(2, "exp_b")])) + self.assertEqual(1, context.get_treatment("exp_a")) + self.assertEqual( + [self.exposure(1, "exp_a", 1, assigned=False, overridden=True)], + self.exposure_tuples(context.exposures)) + + def test_exposed_override_is_not_exposed_again_when_its_id_changes(self): + context = self.create_context(context_data( + [assigned(1, "exp_a"), assigned(2, "exp_b")]), + overrides={"exp_a": 1}) + self.assertEqual(1, context.get_treatment("exp_a")) + self.refresh(context, context_data( + [assigned(5, "exp_a"), assigned(2, "exp_b")])) + self.assertEqual(1, context.get_treatment("exp_a")) + self.assertEqual( + [self.exposure(1, "exp_a", 1, assigned=False, overridden=True)], + self.exposure_tuples(context.exposures)) + + def test_override_kept_from_before_an_id_0_experiment_gets_its_value( + self): + # The override is cached while exp_a is missing; a refresh adds exp_a + # with id 0, so the cache keeps the override, which must then carry + # the experiment's variables instead of returning the default. + context = self.create_context(context_data([assigned(2, "exp_b")]), + overrides={"exp_a": 1}) + context.peek_treatment("exp_a") + self.refresh(context, context_data( + [assigned(0, "exp_a"), assigned(2, "exp_b")])) + self.assertEqual("exp_a_treatment", + context.peek_variable_value(KEY, "d")) + self.assertEqual("exp_a_treatment", + context.get_variable_value(KEY, "d")) + + def test_kept_override_keeps_its_variables_across_a_config_change(self): + context = self.create_context(context_data( + [assigned(1, "exp_a"), assigned(2, "exp_b")]), + overrides={"exp_a": 1}) + self.assertEqual("exp_a_treatment", + context.get_variable_value(KEY, "d")) + changed = with_variables(experiment(1, "exp_a"), KEY, + "exp_a_control2", "exp_a_t2") + self.refresh(context, context_data([changed, assigned(2, "exp_b")])) + self.assertEqual("exp_a_treatment", + context.get_variable_value(KEY, "d")) + + def test_negative_override_never_reads_a_variant_from_the_end(self): + context = self.create_context(context_data( + [assigned(1, "exp_a"), assigned(2, "exp_b")]), + overrides={"exp_a": -1}) + self.assertEqual(["d", "d", "d"], + [context.get_variable_value(KEY, "d"), + context.get_variable_value(KEY, "d"), + context.peek_variable_value(KEY, "d")]) + + def test_override_to_a_missing_variant_takes_it_once_a_refresh_adds_it( + self): + # Same experiment (id 1) throughout: the kept override gets the new + # variant's variables, as JS followArm does. + two = configs(1, "exp_a", {KEY: "a0"}, {KEY: "a1"}) + context = self.create_context(context_data( + [two, assigned(9, "exp_b")]), overrides={"exp_a": 2}) + self.assertEqual("d", context.get_variable_value(KEY, "d")) + three = configs(1, "exp_a", {KEY: "a0"}, {KEY: "a1"}, {KEY: "a2"}) + self.refresh(context, context_data([three, assigned(9, "exp_b")])) + self.assertEqual(["a2", "a2"], + [context.get_variable_value(KEY, "d"), + context.peek_variable_value(KEY, "d")]) + self.assertEqual(["exp_a"], self.names(context)) + + def test_override_to_a_missing_variant_of_a_reidentified_experiment( + self): + # The override names a variant exp_a does not have; a refresh adds + # that variant but also gives exp_a a new id: the kept override is + # not for the same experiment, so it does not take the new value. + two = configs(1, "exp_a", {KEY: "a0"}, {KEY: "a1"}) + context = self.create_context(context_data( + [two, assigned(9, "exp_b")]), overrides={"exp_a": 2}) + self.assertEqual("d", context.get_variable_value(KEY, "d")) + three = configs(7, "exp_a", {KEY: "a0"}, {KEY: "a1"}, {KEY: "a2"}) + self.refresh(context, context_data([three, assigned(9, "exp_b")])) + self.assertEqual("d", context.get_variable_value(KEY, "d")) + self.assertEqual(["exp_a"], self.names(context)) + + def test_override_of_an_experiment_with_id_0_is_exposed_once(self): + context = self.create_context(context_data([assigned(0, "exp_a")]), + overrides={"exp_a": 1}) + for _ in range(3): + self.assertEqual("exp_a_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual(1, context.get_treatment("exp_a")) + self.assertEqual(1, context.get_pending_count()) + + def test_final_walk_replaced_by_a_keyless_experiment_exposes_nothing( + self): + # On every walk a refresh swaps exp_a for a same-name experiment + # that no longer defines the key. The final walk must not expose + # that replacement or return its default as if it had won. + keyed = assigned(1, "exp_a") + keyless = configs(1, "exp_a", {"other": "x"}, {"other": "y"}) + context = self.create_context(context_data( + [keyed, assigned(2, "exp_b")])) + get_assignment = context.get_assignment + + def swap(name, exposed_at=None): + if name == "exp_a": + self.refresh(context, context_data( + [keyless, assigned(2, "exp_b")])) + assignment = get_assignment(name, exposed_at=exposed_at) + self.refresh(context, context_data( + [keyed, assigned(2, "exp_b")])) + return assignment + return get_assignment(name, exposed_at=exposed_at) + + context.get_assignment = swap + self.assertEqual("d", context.get_variable_value(KEY, "d")) + self.assertEqual([], self.names(context)) + + def test_declined_holdout_is_offered_once_per_read_across_retries(self): + # The hook declines holdout_b and adds an unrelated unit, so the + # read walks again; the retry must not offer holdout_b a second + # time in the same read. The next read offers it again. + from sdk.context import Context + offered = [] + + class Declining(Context): + def queue_exposure(self, assignment): + offered.append(assignment.name) + if assignment.name == "holdout_b": + if self.get_unit("other_id") is None: + self.set_unit("other_id", UID) + return None + return super().queue_exposure(assignment) + + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a", holdout_ids=[12]), + assigned(2, "exp_b")], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)])) + context.__class__ = Declining + self.assertEqual("exp_b_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual(1, offered.count("holdout_b")) + context.get_variable_value(KEY, "d") + self.assertEqual(2, offered.count("holdout_b")) + + def test_close_on_a_shared_holdout_reached_through_a_loser(self): + # exp_a loses and shares holdout_b with the winner exp_b. Closing + # from the logger on holdout_b must publish exp_b with it. + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a", holdout_ids=[12]), + assigned(2, "exp_b", holdout_ids=[12])], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)])) + + def close_on_holdout(event_type, data): + if event_type == EventType.EXPOSURE and \ + data.name == "holdout_b": + self.logger.on_event = None + context.close_async() + + self.logger.on_event = close_on_holdout + self.assertEqual("exp_b_treatment", + context.get_variable_value(KEY, "d")) + self.client.wait_for_publish(1) + self.assertEqual( + [self.holdout_exposure(12, "holdout_b", 1), + self.exposure(2, "exp_b", NORMAL_VARIANT)], + self.exposure_tuples(self.client.published[0].exposures)) + + def test_shared_holdout_loser_is_skipped_on_warm_reads(self): + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a", holdout_ids=[12]), + assigned(2, "exp_b", holdout_ids=[12])], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)])) + context.get_variable_value(KEY, "d") + self.assertTrue(context.get_assignment("exp_a").holdouts_exposed) + self.assertEqual(["holdout_b", "exp_b"], self.names(context)) + + def test_override_variables_fill_reads_the_payload_it_stores(self): + # The read passes the cache check while exp_a's variant 2 is X; a + # refresh changes it to Y before the fill. The fill must store Y, + # the payload current when it stores, not the X it checked. + two = configs(1, "exp_a", {KEY: "a0"}, {KEY: "a1"}) + with_x = configs(1, "exp_a", {KEY: "a0"}, {KEY: "a1"}, {KEY: "X"}) + with_y = configs(1, "exp_a", {KEY: "a0"}, {KEY: "a1"}, {KEY: "Y"}) + context = self.create_context(context_data( + [two, assigned(9, "exp_b")]), overrides={"exp_a": 2}) + self.assertEqual("d", context.get_variable_value(KEY, "d")) + self.refresh(context, context_data([with_x, assigned(9, "exp_b")])) + lock = context.context_lock + acquire_write = lock.acquire_write + refreshed = [] + + def refresh_before_the_fill(): + lock.acquire_write = acquire_write + refreshed.append(1) + self.refresh(context, context_data( + [with_y, assigned(9, "exp_b")])) + acquire_write() + + lock.acquire_write = refresh_before_the_fill + self.assertEqual("Y", context.peek_variable_value(KEY, "d")) + self.assertEqual([1], refreshed) + self.assertEqual("Y", context.get_variable_value(KEY, "d")) + + def test_override_fill_skips_an_experiment_a_refresh_reidentified(self): + # The read passes the cache check for exp_a (id 1); a refresh moves + # exp_a to id 5 before the fill. The kept override is no longer for + # the same experiment, so the fill stores nothing. + two = configs(1, "exp_a", {KEY: "a0"}, {KEY: "a1"}) + with_x = configs(1, "exp_a", {KEY: "a0"}, {KEY: "a1"}, {KEY: "X"}) + moved = configs(5, "exp_a", {KEY: "a0"}, {KEY: "a1"}, {KEY: "Y"}) + context = self.create_context(context_data( + [two, assigned(9, "exp_b")]), overrides={"exp_a": 2}) + self.assertEqual("d", context.get_variable_value(KEY, "d")) + self.refresh(context, context_data([with_x, assigned(9, "exp_b")])) + lock = context.context_lock + acquire_write = lock.acquire_write + + def refresh_before_the_fill(): + lock.acquire_write = acquire_write + self.refresh(context, context_data( + [moved, assigned(9, "exp_b")])) + acquire_write() + + lock.acquire_write = refresh_before_the_fill + self.assertEqual("d", context.peek_variable_value(KEY, "d")) + self.assertIsNone(context.get_assignment("exp_a").variables) + + def test_loser_sharing_a_holdout_keeps_it_pending_if_the_winner_fails( + self): + # exp_a loses and shares holdout_b with the winner exp_b, so the + # arm waits for exp_b's section. A close then rejects exp_b and + # fails; a refresh removes the holdout from exp_b. The next read must + # still publish holdout_b through exp_a. + from sdk.context_error import ContextError + holdouts = [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)] + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a", holdout_ids=[12]), + assigned(2, "exp_b", holdout_ids=[12])], holdouts)) + expose_winner = context._expose_winner + + def closing(assignment): + context.closing.set(True) + try: + return expose_winner(assignment) + finally: + context.closing.set(False) + + context._expose_winner = closing + with self.assertRaises(ContextError): + context.get_variable_value(KEY, "d") + context._expose_winner = expose_winner + self.assertEqual([], self.names(context)) + self.refresh(context, context_data( + [strict_mismatch(1, "exp_a", holdout_ids=[12]), + assigned(2, "exp_b")], holdouts)) + self.assertEqual("exp_b_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual(["holdout_b", "exp_b"], self.names(context)) + + def test_winner_retired_on_every_attempt_returns_the_default(self): + # set_unit retires the winner each time it is about to be exposed; + # after the last attempt the read returns the default, not the value + # of a winner that was never exposed. + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a"), assigned(2, "exp_b")])) + expose_winner = context._expose_winner + attempts = [] + + def retire_first(assignment): + attempts.append(assignment.name) + context._retire(assignment) + return expose_winner(assignment) + + context._expose_winner = retire_first + self.assertEqual("d", context.get_variable_value(KEY, "d")) + self.assertEqual(["exp_b", "exp_b", "exp_b"], attempts) + self.assertEqual([], self.names(context)) + + def test_hook_returning_false_is_a_decline_not_a_retirement(self): + # v0.2.4 hooks may return False. Without holdouts that must not look + # like set_unit retiring the winner: the value comes back and the + # hook is called once per read, as in 0.3.0. + from sdk.context import Context + calls = [] + + class Declining(Context): + def queue_exposure(self, assignment): + calls.append(assignment.name) + return False + + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a"), assigned(2, "exp_b")])) + context.__class__ = Declining + self.assertEqual("exp_b_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual(["exp_b"], calls) + self.assertEqual(NORMAL_VARIANT, context.get_treatment("exp_b")) + self.assertEqual(["exp_b", "exp_b"], calls) + + def test_hook_seeing_the_winner_retired_walks_the_key_again(self): + # Without holdouts: exp_a (user_id) is missing its unit, so exp_b + # wins. Its override, while being offered exp_b, adds user_id and + # retires exp_b, the winner it was offered, then does not queue it. + # Judged by the assignment's state, the read walks again and exp_a + # wins. + from sdk.context import Context + + class SettingUnit(Context): + def queue_exposure(self, assignment): + if assignment.name == "exp_b" and \ + self.get_unit("user_id") is None: + self.set_unit("user_id", UID) + self._retire(assignment) + return None + return super().queue_exposure(assignment) + + context = self.create_context(context_data( + [assigned(1, "exp_a", unit_type="user_id"), + assigned(2, "exp_b")])) + context.__class__ = SettingUnit + self.assertEqual("exp_a_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual(["exp_a"], self.names(context)) + + def test_treatment_hook_judged_by_state_after_it_adds_the_unit(self): + # exp_a is overridden on a missing unit. On its first call the hook + # adds the unit (retiring the assignment it was handed) without + # queuing it; get_treatment must resolve again and queue exactly one + # exposure for the fresh assignment. + from sdk.context import Context + seen = [] + + class SettingUnit(Context): + def queue_exposure(self, assignment): + seen.append(self.get_unit("device_id")) + if self.get_unit("device_id") is None: + self.set_unit("device_id", "dev-1") + return None + return super().queue_exposure(assignment) + + context = self.create_context(context_data( + [missing_unit(1, "exp_a")]), units={}, overrides={"exp_a": 1}) + context.__class__ = SettingUnit + self.assertEqual(1, context.get_treatment("exp_a")) + self.assertEqual([None, "dev-1"], seen) + self.assertEqual(1, context.get_pending_count()) + + def test_hook_is_never_handed_a_retired_assignment(self): + # set_unit lands between resolving the assignment and exposing it: + # the hook is called once, with the fresh assignment. + from sdk.context import Context + handed = [] + + class Recording(Context): + def queue_exposure(self, assignment): + handed.append((assignment.retired, assignment.assigned)) + return super().queue_exposure(assignment) + + context = self.create_context(context_data( + [missing_unit(1, "exp_a")]), units={}) + context.__class__ = Recording + get_assignment = context.get_assignment + calls = [] + + def set_unit_after_first(name, exposed_at=None): + assignment = get_assignment(name, exposed_at=exposed_at) + if not calls: + calls.append(name) + context.set_unit("device_id", "dev-1") + return assignment + + context.get_assignment = set_unit_after_first + context.get_treatment("exp_a") + self.assertEqual([(False, True)], handed) + self.assertEqual(1, context.get_pending_count()) + + def test_offered_arms_are_tracked_by_object_not_id(self): + # Pins how the per-read set stores arms: by the arm itself, kept + # alive for the read, not by id(). A stale id in the set (as a + # released arm's id reused by a new one would leave) must not stop + # the arm being offered. A real read cannot easily force the reuse, + # so the set is seeded directly. + from sdk.context import Context + offered_to_hook = [] + + class Declining(Context): + def queue_exposure(self, assignment): + offered_to_hook.append(assignment.name) + return None + + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a", holdout_ids=[12]), + assigned(2, "exp_b")], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)])) + context.__class__ = Declining + loser = context.get_assignment("exp_a") + arm = loser.holdout_assignments[0] + offered = {id(arm)} + context._offer_holdouts_through_hook(loser, 1, offered) + self.assertEqual(["holdout_b"], offered_to_hook) + self.assertIn(arm, offered) + + def test_set_unit_retiring_the_winner_before_exposure_walks_again(self): + # exp_b wins while exp_a's unit is missing; the unit arrives as + # exp_b is exposed and retires it, so the read walks again and + # returns and exposes exp_a, which wins with the unit. + context = self.create_context(context_data( + [missing_unit(1, "exp_a"), + assigned(2, "exp_b", unit_type="device_id", + holdout_ids=[12])], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS, + unit_type="device_id")]), + units={}, overrides={"exp_b": 1}) + expose_winner = context._expose_winner + calls = [] + + def set_unit_first(assignment): + if not calls: + calls.append(assignment.name) + context.set_unit("device_id", UID) + return expose_winner(assignment) + + context._expose_winner = set_unit_first + self.assertEqual("exp_a_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual(["exp_b"], calls) + self.assertEqual(["exp_a"], self.names(context)) + + def test_warm_read_skips_holdouts_already_exposed(self): + context = self.create_context(context_data( + [strict_mismatch(1, "exp_a", holdout_ids=[12]), + assigned(2, "exp_b")], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)])) + context.get_variable_value(KEY, "d") + calls = [] + expose_holdouts = context._expose_holdouts + context._expose_holdouts = \ + lambda assignment: calls.append(1) or expose_holdouts(assignment) + for _ in range(3): + self.assertEqual("exp_b_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual([], calls) + + def test_experiment_removed_by_a_refresh_during_the_walk_cannot_win(self): + # exp_a is overridden, so its placeholder would claim the key once a + # refresh removed it; the remaining candidate wins instead. + context = self.create_context(context_data( + [assigned(1, "exp_a"), assigned(2, "exp_b")]), + overrides={"exp_a": 1}) + get_assignment = context.get_assignment + refreshed = [] + + def refresh_first(name, exposed_at=None): + if not refreshed: + refreshed.append(name) + self.refresh(context, context_data([assigned(2, "exp_b")])) + return get_assignment(name, exposed_at=exposed_at) + + context.get_assignment = refresh_first + self.assertEqual("exp_b_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual([self.exposure(2, "exp_b", NORMAL_VARIANT)], + self.exposure_tuples(context.exposures)) + + def test_close_cannot_publish_the_winner_holdouts_without_the_winner(self): + # Closing from the logger on the holdout exposure publishes the + # winner's whole group, accepted before the logger runs. + context = self.create_context(context_data( + [assigned(1, "exp_a", holdout_ids=[12])], + [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)])) + + def close_on_holdout(event_type, data): + if event_type == EventType.EXPOSURE and \ + data.name == "holdout_b": + self.logger.on_event = None + context.close_async() + + self.logger.on_event = close_on_holdout + self.assertEqual("exp_a_treatment", + context.get_variable_value(KEY, "d")) + self.client.wait_for_publish(1) + self.assertEqual( + [self.holdout_exposure(12, "holdout_b", 1), + self.exposure(1, "exp_a", NORMAL_VARIANT)], + self.exposure_tuples(self.client.published[0].exposures)) + + +if __name__ == "__main__": + unittest.main()