From 395e44a2ef3f16a4b122a22a8d60c39dc3c9f6a0 Mon Sep 17 00:00:00 2001 From: lux worker Date: Mon, 23 Nov 2026 23:07:15 +0000 Subject: [PATCH 01/27] fix: only the winning experiment is exposed for a shared variable key A shared variable key queued an exposure for every experiment visited on the way to its value, including ones the unit was not in, and fell through to the next experiment when the winner's variant lacked the key. Port Java's getVariableAssignment: the first assigned, overridden or rule-assigned candidate (by id) wins, its variant alone decides the value, and only it is exposed. Visited candidates still fire their holdouts. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 + README.md | 11 +- sdk/context.py | 115 ++++++++++---- test/test_context.py | 49 +++--- test/test_context_holdouts.py | 8 +- test/test_holdout_contracts.py | 49 ++++-- test/test_shared_variable_keys.py | 252 ++++++++++++++++++++++++++++++ 7 files changed, 409 insertions(+), 78 deletions(-) create mode 100644 test/test_shared_variable_keys.py diff --git a/CHANGELOG.md b/CHANGELOG.md index d1694c3..851c44c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ - 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), 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. 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 - 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..f1f6339 100644 --- a/README.md +++ b/README.md @@ -229,6 +229,15 @@ 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) get no exposure. +- If no experiment wins, a held-out experiment defining the key supplies its control value (see [Holdouts](#holdouts)); otherwise the default is returned and nothing is exposed. +- `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 +306,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..b0aa0c0 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -1062,41 +1062,46 @@ def peek_variable_value(self, key: str, default_value: object): 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. + assignment = self._variable_assignment(key, expose) + if expose and assignment is not None and \ + (not assignment.exposed.value or + assignment.holdouts_pending) and \ + not self._expose(assignment) and \ + attempt < _MAX_EXPOSURE_ATTEMPTS: + # set_unit retired the winner in between, so the key may + # resolve differently: walk it again. + return self._variable_value(key, default_value, expose, + attempt + 1) + if assignment is not None and assignment.variables is not None and \ + key in assignment.variables: + return assignment.variables[key] + return default_value + + def _variable_assignment(self, key: str, expose: bool): + # 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 as it is visited (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). experiments = Concurrency.get_rw( self.data_lock, self.index_variables, key) or [] suppressed_fallback = None 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 + if expose: + self._expose_holdouts(assignment) + if assignment.assigned or assignment.overridden or \ + assignment.rule_override: + return assignment + if assignment.suppressed and suppressed_fallback is None: + suppressed_fallback = assignment + return suppressed_fallback def peek_treatment(self, experiment_name: str): self.check_ready(True) @@ -1837,6 +1842,13 @@ def _expose_through_hook(self, assignment: Assignment): # retried. if not assignment.exposed.value and assignment.retired: return False + if self._offer_holdouts_through_hook(assignment, exposed_at): + assignment.holdouts_pending = False + return True + + def _offer_holdouts_through_hook(self, assignment: Assignment, + exposed_at): + # True when every holdout pinned on the assignment is exposed. finished = True for holdout, holdout_assignment in zip( assignment.holdouts, assignment.holdout_assignments): @@ -1867,9 +1879,46 @@ def _expose_through_hook(self, assignment: Assignment): holdout_assignment.hook_pending = False if not holdout_assignment.exposed.value: finished = False - if finished: - assignment.holdouts_pending = False - return True + return finished + + def _expose_holdouts(self, assignment: Assignment): + """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 \ + all(holdout_assignment is None or + holdout_assignment.exposed.value + for holdout_assignment in assignment.holdout_assignments): + 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) + return + + accepted = [] + try: + self.event_lock.acquire_write() + self.check_not_closed() + for holdout, holdout_assignment in zip( + assignment.holdouts, assignment.holdout_assignments): + if holdout_assignment is not None: + exposure = self._accept_exposure( + holdout_assignment, holdout.name, exposed_at) + if exposure is not None: + accepted.append(exposure) + finally: + self.event_lock.release_write() + + for exposure in accepted: + self.log_event(EventType.EXPOSURE, exposure) + if accepted: + self.set_timeout() 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..5342bad 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,8 @@ 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]) + # exp_a was only checked: it is not exposed. + self.assertEqual(["exp_b"], [e.name for e in context.exposures]) context.set_override("exp_a", 1) self.assertEqual("a_treatment", @@ -2005,10 +2008,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 +2025,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..2e07183 --- /dev/null +++ b/test/test_shared_variable_keys.py @@ -0,0 +1,252 @@ +"""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 test.holdout_fixtures import ( + HOLDOUT_B_SEEDS, NORMAL_VARIANT, 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, **kwargs): + context = self.create_context(context_data(experiments), **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()) + # A second read exposes nothing more. + 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_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): + # The unit gets exp_a's variant 1, which does not define the key: + # the default is returned and exp_b is never consulted or exposed. + self.assert_winner( + [configs(1, "exp_a", {KEY: "a0"}, {"other": "x"}), + assigned(2, "exp_b")], + "d", ["exp_a"]) + + 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. + 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"]) + + 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_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) + + +if __name__ == "__main__": + unittest.main() From 02437939a914ccd8de845be416038709e252f1ee Mon Sep 17 00:00:00 2001 From: lux worker Date: Mon, 23 Nov 2026 23:48:36 +0000 Subject: [PATCH 02/27] fix: a raising hook does not stop the shared-key walk; pin the loser holdout path Like Java's getVariableAssignment, a queue_exposure hook raising on one holdout no longer stops the remaining holdouts and candidates: the first error is raised once the walk ends. Tests pin the closing check, the snapshot name and the warm-read fast path of the loser holdout exposure. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + sdk/context.py | 28 ++++++++++-- test/test_shared_variable_keys.py | 71 +++++++++++++++++++++++++++++++ 3 files changed, 96 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 851c44c..34eae47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - 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), 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. 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 sharing a variable key: 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. - 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/sdk/context.py b/sdk/context.py index b0aa0c0..7212e5e 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -1089,19 +1089,30 @@ def _variable_assignment(self, key: str, expose: bool): # 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 the winner is found, as in Java. experiments = Concurrency.get_rw( self.data_lock, self.index_variables, key) or [] suppressed_fallback = None + failure = None for experiment in list(experiments): assignment = self.get_assignment(experiment.data.name) if expose: - self._expose_holdouts(assignment) + try: + self._expose_holdouts(assignment) + except Exception as error: + if failure is None: + failure = error if assignment.assigned or assignment.overridden or \ assignment.rule_override: - return assignment + break if assignment.suppressed and suppressed_fallback is None: suppressed_fallback = assignment - return suppressed_fallback + else: + assignment = suppressed_fallback + if failure is not None: + raise failure + return assignment def peek_treatment(self, experiment_name: str): self.check_ready(True) @@ -1848,8 +1859,12 @@ def _expose_through_hook(self, assignment: Assignment): def _offer_holdouts_through_hook(self, assignment: Assignment, exposed_at): - # True when every holdout pinned on the assignment is exposed. + # 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: @@ -1875,10 +1890,15 @@ def _offer_holdouts_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 failure is not None: + raise failure return finished def _expose_holdouts(self, assignment: Assignment): diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index 2e07183..c9569dd 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -241,6 +241,77 @@ def queue_exposure(self, assignment): 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) + + 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") + 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) + + 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 + + class Raising(Context): + def queue_exposure(self, assignment): + if assignment.name == "h1" and \ + not assignment.exposed.value: + raise RuntimeError("hook 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, "hook failed"): + context.get_variable_value(KEY, "d") + self.assertEqual(["h2", "h3"], self.names(context)) + def test_unit_type_of_exposure(self): context = self.assert_winner( [missing_unit(1, "exp_a"), assigned(2, "exp_b")], From 538930dde4f7c66bf01f8ac9a808ea1ab21d4cc3 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 00:38:36 +0000 Subject: [PATCH 03/27] perf: skip a shared-key candidate's holdouts once all are exposed; pin logging and missing-variant overrides Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +- sdk/context.py | 21 +++++++++++-- test/test_shared_variable_keys.py | 49 +++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 34eae47..48d7207 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,8 @@ - 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), 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. 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 sharing a variable key: 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. +- Exposure counts change for experiments sharing a variable key: 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 `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/sdk/context.py b/sdk/context.py index 7212e5e..a39d9b2 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 + # Every holdout pinned on this assignment is exposed, so a variable + # read visiting it skips them (see Context._expose_holdouts). + self.holdouts_exposed: bool = False class ExperimentVariables: @@ -1911,14 +1914,18 @@ def _expose_holdouts(self, assignment: Assignment): read. """ if assignment.holdout_assignments is None or \ - all(holdout_assignment is None or - holdout_assignment.exposed.value - for holdout_assignment in assignment.holdout_assignments): + assignment.holdouts_exposed: + return + if not self._holdouts_unexposed(assignment): + # The pinned arms never change and stay exposed. + assignment.holdouts_exposed = 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) + assignment.holdouts_exposed = \ + not self._holdouts_unexposed(assignment) return accepted = [] @@ -1935,11 +1942,19 @@ def _expose_holdouts(self, assignment: Assignment): finally: self.event_lock.release_write() + # Each arm is now exposed, by this read or an earlier one. + assignment.holdouts_exposed = True for exposure in accepted: self.log_event(EventType.EXPOSURE, exposure) if accepted: self.set_timeout() + @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, # None when there is nothing to queue, False when retired. diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index c9569dd..6bd3fd5 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -280,13 +280,42 @@ def test_warm_read_takes_no_event_lock(self): 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_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_raising_hook_does_not_stop_the_other_holdouts(self): # Java collects the first failure, fires every visited candidate's @@ -312,6 +341,26 @@ def queue_exposure(self, assignment): context.get_variable_value(KEY, "d") self.assertEqual(["h2", "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")], From d0a8aec4f1cc5ad60af7e8c63d7d453b7308a198 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 01:03:30 +0000 Subject: [PATCH 04/27] test: pin the shared-key holdout flag across a failed close, the pre-exposed skip and the exposure time Co-Authored-By: Claude Opus 5.5 --- test/test_shared_variable_keys.py | 36 +++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index 6bd3fd5..129319d 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -258,6 +258,14 @@ def test_losing_candidate_holdouts_are_not_queued_while_closing(self): 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 @@ -294,6 +302,34 @@ def test_warm_read_takes_no_event_lock(self): 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_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 = [] From 582c1101815ecebcb6f75d2c3b89b57aeef1b23f Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 16:27:01 +0000 Subject: [PATCH 05/27] fix: offer a shared-key winner's holdouts once per read; document lone-candidate exposure loss The variable walk already offers the winner's holdouts, so _expose no longer offers them again (a declining queue_exposure override saw the same holdout twice in one read). holdouts_pending is cleared when the walk exposes them, and _variable_value no longer re-exposes on it. CHANGELOG and README now say that an experiment the unit is not in is no longer exposed by get_variable_value even when it alone defines the key. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++-- README.md | 1 + sdk/context.py | 33 +++++++++++++++++--------- test/test_shared_variable_keys.py | 39 +++++++++++++++++++++++++++++++ 4 files changed, 64 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 48d7207..968cef1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,10 +7,10 @@ - `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), 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. 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. +- 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), 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 nothing is exposed. `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 sharing a variable key: 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). +- 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) 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 `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 f1f6339..d56625f 100644 --- a/README.md +++ b/README.md @@ -235,6 +235,7 @@ When several experiments define the same variable key (in any of their variants) - 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) get no exposure. +- 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), nothing wins, the default is returned and nothing is exposed. `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 nothing is exposed. - `peek_variable_value` resolves the same winner and exposes nothing. diff --git a/sdk/context.py b/sdk/context.py index a39d9b2..d993d07 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -1066,10 +1066,11 @@ def peek_variable_value(self, key: str, default_value: object): def _variable_value(self, key: str, default_value: object, expose: bool, attempt: int = 1): assignment = self._variable_assignment(key, expose) + # The walk offered the winner's holdouts, and offers any left + # unexposed again on the next read: only its own exposure is left. if expose and assignment is not None and \ - (not assignment.exposed.value or - assignment.holdouts_pending) and \ - not self._expose(assignment) and \ + not assignment.exposed.value and \ + not self._expose(assignment, offer_holdouts=False) and \ attempt < _MAX_EXPOSURE_ATTEMPTS: # set_unit retired the winner in between, so the key may # resolve differently: walk it again. @@ -1756,7 +1757,7 @@ 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): """Expose an assignment; False when set_unit retired it first. JS _triggerExposures: a held-out experiment publishes no exposure of @@ -1766,13 +1767,16 @@ 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 offer_holdouts=False: its walk already offered the holdouts + (_expose_holdouts), so a queue_exposure override is not offered a + declined one 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 not \ Context.queue_exposure: - return self._expose_through_hook(assignment) + return self._expose_through_hook(assignment, offer_holdouts) accepted = [] try: @@ -1791,7 +1795,7 @@ def _expose(self, assignment: Assignment): accepted.append(exposure) for holdout, holdout_assignment in zip( assignment.holdouts, assignment.holdout_assignments): - if holdout_assignment is not None: + if offer_holdouts and holdout_assignment is not None: # Named from this assignment's snapshot, like JS # holdouts[i].data.name; the shared holdout assignment # is not modified. @@ -1808,7 +1812,8 @@ def _expose(self, assignment: Assignment): 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. @@ -1856,7 +1861,10 @@ def _expose_through_hook(self, assignment: Assignment): # retried. if not assignment.exposed.value and assignment.retired: return False - if self._offer_holdouts_through_hook(assignment, exposed_at): + 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 @@ -1919,13 +1927,15 @@ def _expose_holdouts(self, assignment: Assignment): if not self._holdouts_unexposed(assignment): # The pinned arms never change and stay exposed. assignment.holdouts_exposed = True + assignment.holdouts_pending = False 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) - assignment.holdouts_exposed = \ - not self._holdouts_unexposed(assignment) + if not self._holdouts_unexposed(assignment): + assignment.holdouts_exposed = True + assignment.holdouts_pending = False return accepted = [] @@ -1944,6 +1954,7 @@ def _expose_holdouts(self, assignment: Assignment): # Each arm is now exposed, by this read or an earlier one. assignment.holdouts_exposed = True + assignment.holdouts_pending = False for exposure in accepted: self.log_event(EventType.EXPOSURE, exposure) if accepted: diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index 129319d..db831eb 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -76,6 +76,14 @@ def test_lower_id_without_its_unit_is_not_exposed(self): [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"), @@ -353,6 +361,37 @@ def queue_exposure(self, assignment): 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) + # The next read offers the declined holdout again, and only it. + 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 bb98367071cf885cfe062a563c3503077af4822c Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 16:55:18 +0000 Subject: [PATCH 06/27] test: pin that a hook-path variable read leaves the winner's holdouts not pending Co-Authored-By: Claude Opus 5.5 --- test/test_shared_variable_keys.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index db831eb..3fb4474 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -326,6 +326,31 @@ def test_holdouts_exposed_by_a_treatment_take_no_event_lock(self): 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. From 4eeddbb410192b416452fcfd3b3beb8edd8973f7 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 17:04:36 +0000 Subject: [PATCH 07/27] docs: distinguish experiment exposures from candidate holdout exposures Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 968cef1..4196d06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ - `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), 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 nothing is exposed. `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. +- 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), 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) 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). diff --git a/README.md b/README.md index d56625f..db7f415 100644 --- a/README.md +++ b/README.md @@ -235,7 +235,7 @@ When several experiments define the same variable key (in any of their variants) - 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) get no exposure. -- 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), nothing wins, the default is returned and nothing is exposed. `get_treatment` still exposes that experiment. +- 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), 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 nothing is exposed. - `peek_variable_value` resolves the same winner and exposes nothing. From f67458fe8105f437c89109a810b05a7f7d9db312 Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 26 Nov 2026 21:25:21 +0000 Subject: [PATCH 08/27] fix: make shared-key selection safe across lifecycle races Co-Authored-By: Claude Opus 5.5 --- sdk/context.py | 96 ++++++++++++++++++++----------- test/test_shared_variable_keys.py | 17 +++--- 2 files changed, 73 insertions(+), 40 deletions(-) diff --git a/sdk/context.py b/sdk/context.py index d993d07..dc92514 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -87,6 +87,8 @@ def __init__(self): # Every holdout pinned on this assignment is exposed, so a variable # read visiting it skips them (see Context._expose_holdouts). self.holdouts_exposed: bool = False + # A candidate retired while the shared-key walk was in progress. + self.selection_invalidated: bool = False class ExperimentVariables: @@ -1066,14 +1068,22 @@ def peek_variable_value(self, key: str, default_value: object): def _variable_value(self, key: str, default_value: object, expose: bool, attempt: int = 1): assignment = self._variable_assignment(key, expose) - # The walk offered the winner's holdouts, and offers any left - # unexposed again on the next read: only its own exposure is left. + if expose and assignment is not None and \ + assignment.selection_invalidated and \ + attempt < _MAX_EXPOSURE_ATTEMPTS: + return self._variable_value(key, default_value, expose, + attempt + 1) + # The walk offers losing candidates' holdouts. For the winner, the + # built-in path queues the experiment and its holdouts together so a + # close cannot drain only half of the winner group; hook paths have + # already offered the holdouts and retain the separate calls. + offer_holdouts = getattr(self.queue_exposure, "__func__", None) is \ + Context.queue_exposure if expose and assignment is not None and \ not assignment.exposed.value and \ - not self._expose(assignment, offer_holdouts=False) and \ + not self._expose(assignment, offer_holdouts=offer_holdouts, + holdouts_first=offer_holdouts) and \ attempt < _MAX_EXPOSURE_ATTEMPTS: - # set_unit retired the winner in between, so the key may - # resolve differently: walk it again. return self._variable_value(key, default_value, expose, attempt + 1) if assignment is not None and assignment.variables is not None and \ @@ -1082,31 +1092,24 @@ def _variable_value(self, key: str, default_value: object, expose: bool, return default_value def _variable_assignment(self, key: str, expose: bool): - # 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 as it is visited (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 the winner is found, as in Java. + # Port of the Java SDK's getVariableAssignment. Candidates are + # ordered by id; the first assigned, overridden, or rule-assigned + # candidate wins, while the first suppressed candidate is the + # fallback. Losing candidates publish only their holdouts. experiments = Concurrency.get_rw( self.data_lock, self.index_variables, key) or [] suppressed_fallback = None failure = None + visited = [] for experiment in list(experiments): assignment = self.get_assignment(experiment.data.name) - if expose: - try: - self._expose_holdouts(assignment) - except Exception as error: - if failure is None: - failure = error + # A refresh may have removed the indexed experiment between the + # index read and resolution; its placeholder must not win. + if assignment.id == 0 and self.get_experiment( + experiment.data.name) is None: + assignment.selection_invalidated = True + continue + visited.append(assignment) if assignment.assigned or assignment.overridden or \ assignment.rule_override: break @@ -1114,6 +1117,23 @@ def _variable_assignment(self, key: str, expose: bool): suppressed_fallback = assignment else: assignment = suppressed_fallback + if assignment is None: + return None + assignment.selection_invalidated = any( + candidate.retired for candidate in visited) + if expose: + native = getattr(self.queue_exposure, "__func__", None) is \ + Context.queue_exposure + # Defer the native winner's holdouts to _expose, which accepts + # the winner and all its holdouts under one event-lock section. + for candidate in visited: + if native and candidate is assignment: + continue + try: + self._expose_holdouts(candidate) + except Exception as error: + if failure is None: + failure = error if failure is not None: raise failure return assignment @@ -1757,7 +1777,8 @@ def _retire(self, assignment: Assignment): finally: self.event_lock.release_write() - def _expose(self, assignment: Assignment, offer_holdouts: bool = True): + 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 @@ -1785,14 +1806,18 @@ def _expose(self, assignment: Assignment, offer_holdouts: bool = True): 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) + 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( + assignment, assignment.name, exposed_at) + if exposure is not None: + accepted.append(exposure) + + if not holdouts_first: + accept_assignment() for holdout, holdout_assignment in zip( assignment.holdouts, assignment.holdout_assignments): if offer_holdouts and holdout_assignment is not None: @@ -1803,11 +1828,16 @@ def _expose(self, assignment: Assignment, offer_holdouts: bool = True): holdout_assignment, holdout.name, exposed_at) if exposure is not None: accepted.append(exposure) + if holdouts_first: + accept_assignment() finally: self.event_lock.release_write() for exposure in accepted: self.log_event(EventType.EXPOSURE, exposure) + if offer_holdouts and assignment.holdout_assignments is not None: + assignment.holdouts_exposed = True + assignment.holdouts_pending = False if accepted: self.set_timeout() return True diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index 3fb4474..67ff871 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -95,10 +95,12 @@ def test_winner_exposure_is_the_winning_assignment(self): def test_winner_variant_without_the_key_returns_default(self): # The unit gets exp_a's variant 1, which does not define the key: # the default is returned and exp_b is never consulted or exposed. - self.assert_winner( + context = self.assert_winner( [configs(1, "exp_a", {KEY: "a0"}, {"other": "x"}), - assigned(2, "exp_b")], + assigned(2, "exp_b", holdout_ids=[12])], "d", ["exp_a"]) + 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( @@ -203,11 +205,12 @@ def test_falsy_values_are_returned_and_a_missing_key_is_the_default(self): def test_not_eligible_winner_is_exposed_with_control(self): # Outside traffic is still assigned (variant 0): it wins the key. - self.assert_winner( + 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 @@ -424,9 +427,9 @@ def test_raising_hook_does_not_stop_the_other_holdouts(self): class Raising(Context): def queue_exposure(self, assignment): - if assignment.name == "h1" and \ + if assignment.name in ("h1", "h2") and \ not assignment.exposed.value: - raise RuntimeError("hook failed") + raise RuntimeError(assignment.name + " failed") return super().queue_exposure(assignment) context = self.create_context(context_data( @@ -437,9 +440,9 @@ def queue_exposure(self, assignment): holdout(12, "h2", HOLDOUT_B_SEEDS), holdout(13, "h3", HOLDOUT_B_SEEDS)])) context.__class__ = Raising - with self.assertRaisesRegex(RuntimeError, "hook failed"): + with self.assertRaisesRegex(RuntimeError, "h1 failed"): context.get_variable_value(KEY, "d") - self.assertEqual(["h2", "h3"], self.names(context)) + self.assertEqual(["h3"], self.names(context)) def test_losing_candidate_holdout_exposure_is_logged(self): context = self.create_context(context_data( From 996671c474cece9ab81399598bfb65366ed14c71 Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 26 Nov 2026 21:26:24 +0000 Subject: [PATCH 09/27] style: format shared-key lifecycle changes Co-Authored-By: Claude Opus 5.5 --- sdk/context.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/sdk/context.py b/sdk/context.py index dc92514..efd7c06 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -1081,8 +1081,9 @@ def _variable_value(self, key: str, default_value: object, expose: bool, Context.queue_exposure if expose and assignment is not None and \ not assignment.exposed.value and \ - not self._expose(assignment, offer_holdouts=offer_holdouts, - holdouts_first=offer_holdouts) and \ + not self._expose( + assignment, offer_holdouts=offer_holdouts, + holdouts_first=offer_holdouts) and \ attempt < _MAX_EXPOSURE_ATTEMPTS: return self._variable_value(key, default_value, expose, attempt + 1) @@ -1806,6 +1807,7 @@ def _expose(self, assignment: Assignment, offer_holdouts: bool = True, if assignment.retired: return False exposed_at = assignment.exposedAt or self.clock.millis() + def accept_assignment(): if assignment.suppressed and not assignment.overridden and \ not assignment.rule_override: From a4e5cc9aefcaf4c476fcafb9ba29ceff9d51d186 Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 26 Nov 2026 23:50:36 +0000 Subject: [PATCH 10/27] fix: fire holdouts when no shared-key candidate wins; trim the warm read; pin lifecycle guards A read where no candidate won returned before offering the visited candidates' holdouts, so only the held-out arm published the holdout. The walk now records retirement and pending holdouts as it goes, so a warm read does no extra pass, and the per-assignment invalidation flag is gone. Tests pin set_unit during the walk, a refresh removing an overridden candidate, closing on the winner's holdout, the no-winner holdouts of both arms and the skipped holdout pass. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + sdk/context.py | 102 ++++++++++++++++------------- test/test_shared_variable_keys.py | 103 +++++++++++++++++++++++++++++- 3 files changed, 160 insertions(+), 46 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4196d06..d8be2e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ ### 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) 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 a `set_unit` call retires an experiment the read already checked, the read checks the key again before exposing anything; an experiment a concurrent `refresh` removed never wins the key; and the built-in queue accepts the winner together with its holdouts, so a concurrent close publishes both or neither. - 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/sdk/context.py b/sdk/context.py index efd7c06..303bc3b 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -87,8 +87,6 @@ def __init__(self): # Every holdout pinned on this assignment is exposed, so a variable # read visiting it skips them (see Context._expose_holdouts). self.holdouts_exposed: bool = False - # A candidate retired while the shared-key walk was in progress. - self.selection_invalidated: bool = False class ExperimentVariables: @@ -1067,24 +1065,17 @@ def peek_variable_value(self, key: str, default_value: object): def _variable_value(self, key: str, default_value: object, expose: bool, attempt: int = 1): - assignment = self._variable_assignment(key, expose) - if expose and assignment is not None and \ - assignment.selection_invalidated and \ - attempt < _MAX_EXPOSURE_ATTEMPTS: + assignment, invalidated = self._variable_assignment(key, expose) + retry = attempt < _MAX_EXPOSURE_ATTEMPTS + if expose and invalidated and retry: + # set_unit retired a candidate the walk visited, so the key may + # resolve differently: walk it again before exposing anything. return self._variable_value(key, default_value, expose, attempt + 1) - # The walk offers losing candidates' holdouts. For the winner, the - # built-in path queues the experiment and its holdouts together so a - # close cannot drain only half of the winner group; hook paths have - # already offered the holdouts and retain the separate calls. - offer_holdouts = getattr(self.queue_exposure, "__func__", None) is \ - Context.queue_exposure if expose and assignment is not None and \ not assignment.exposed.value and \ - not self._expose( - assignment, offer_holdouts=offer_holdouts, - holdouts_first=offer_holdouts) and \ - attempt < _MAX_EXPOSURE_ATTEMPTS: + not self._expose_winner(assignment) and retry: + # set_unit retired the winner in between: walk it again. return self._variable_value(key, default_value, expose, attempt + 1) if assignment is not None and assignment.variables is not None and \ @@ -1092,52 +1083,74 @@ def _variable_value(self, key: str, default_value: object, expose: bool, 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): - # Port of the Java SDK's getVariableAssignment. Candidates are - # ordered by id; the first assigned, overridden, or rule-assigned - # candidate wins, while the first suppressed candidate is the - # fallback. Losing candidates publish only their holdouts. + # 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 and whether set_unit retired a visited + # candidate, which makes the caller walk again. experiments = Concurrency.get_rw( self.data_lock, self.index_variables, key) or [] + winner = None suppressed_fallback = None - failure = None - visited = [] + invalidated = False + pending = None for experiment in list(experiments): assignment = self.get_assignment(experiment.data.name) - # A refresh may have removed the indexed experiment between the - # index read and resolution; its placeholder must not win. - if assignment.id == 0 and self.get_experiment( - experiment.data.name) is None: - assignment.selection_invalidated = True + # A refresh removed the indexed experiment after the index was + # read: its placeholder (id 0) must not win, even when overridden. + if assignment.id == 0 and \ + self.get_experiment(experiment.data.name) is None: continue - visited.append(assignment) + invalidated = invalidated or assignment.retired + 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: - assignment = suppressed_fallback - if assignment is None: - return None - assignment.selection_invalidated = any( - candidate.retired for candidate in visited) - if expose: + winner = suppressed_fallback + if pending: native = getattr(self.queue_exposure, "__func__", None) is \ Context.queue_exposure - # Defer the native winner's holdouts to _expose, which accepts - # the winner and all its holdouts under one event-lock section. - for candidate in visited: - if native and candidate is assignment: + failure = None + for candidate in pending: + if native and candidate is winner: + # Accepted with the winner, see _expose_winner. continue try: self._expose_holdouts(candidate) except Exception as error: if failure is None: failure = error - if failure is not None: - raise failure - return assignment + if failure is not None: + raise failure + return winner, invalidated def peek_treatment(self, experiment_name: str): self.check_ready(True) @@ -1790,9 +1803,10 @@ def _expose(self, assignment: Assignment, offer_holdouts: bool = True, 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. A variable read - passes offer_holdouts=False: its walk already offered the holdouts - (_expose_holdouts), so a queue_exposure override is not offered a - declined one twice in a 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 diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index 67ff871..d59a81f 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -5,9 +5,11 @@ import json import unittest +from sdk.context_event_logger import EventType from test.holdout_fixtures import ( - HOLDOUT_B_SEEDS, NORMAL_VARIANT, UNIT_TYPE, HoldoutFixture, context_data, - experiment, holdout, with_variables) + 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( @@ -470,6 +472,103 @@ def test_unit_type_of_exposure(self): "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_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() From 7024e3276a40fc14df2c864478846f85090263a9 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 00:19:19 +0000 Subject: [PATCH 11/27] fix: catch a unit added at any point of a shared-key walk; pin the holdout skip and winner retry The walk only noticed a retirement when it reached the retired candidate, so a set_unit landing after a missing-unit candidate was checked let a later candidate win and be exposed, and the next read exposed the right one too. set_unit now bumps a counter when it adds a unit and the walk compares it before and after. Tests pin that race, the warm-read skip of already exposed holdouts and the retry when the winner is retired just before it is exposed; each fails without its guard. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- sdk/context.py | 20 +++++++--- test/test_shared_variable_keys.py | 64 +++++++++++++++++++++++++++++++ 3 files changed, 79 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d8be2e2..2cf7bcd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ ### 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) 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 a `set_unit` call retires an experiment the read already checked, the read checks the key again before exposing anything; an experiment a concurrent `refresh` removed never wins the key; and the built-in queue accepts the winner together with its holdouts, so a concurrent close publishes both or neither. +- 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 anything; an experiment a concurrent `refresh` removed never wins the key; and the built-in queue accepts the winner together with its holdouts, so a concurrent close publishes both or neither. - 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/sdk/context.py b/sdk/context.py index 303bc3b..ab11e82 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -326,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 = {} @@ -490,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 @@ -1068,8 +1073,8 @@ def _variable_value(self, key: str, default_value: object, expose: bool, assignment, invalidated = self._variable_assignment(key, expose) retry = attempt < _MAX_EXPOSURE_ATTEMPTS if expose and invalidated and retry: - # set_unit retired a candidate the walk visited, so the key may - # resolve differently: walk it again before exposing anything. + # set_unit added a unit during the walk, so the key may resolve + # differently: walk it again before exposing anything. return self._variable_value(key, default_value, expose, attempt + 1) if expose and assignment is not None and \ @@ -1107,13 +1112,13 @@ def _variable_assignment(self, key: str, expose: bool): # 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 and whether set_unit retired a visited - # candidate, which makes the caller walk again. + # Java. Returns the winner and whether set_unit added a unit during + # the walk, which makes the caller walk again. + units_seq = self._units_seq experiments = Concurrency.get_rw( self.data_lock, self.index_variables, key) or [] winner = None suppressed_fallback = None - invalidated = False pending = None for experiment in list(experiments): assignment = self.get_assignment(experiment.data.name) @@ -1122,7 +1127,6 @@ def _variable_assignment(self, key: str, expose: bool): if assignment.id == 0 and \ self.get_experiment(experiment.data.name) is None: continue - invalidated = invalidated or assignment.retired if expose and assignment.holdout_assignments is not None and \ not assignment.holdouts_exposed: pending = pending or [] @@ -1135,6 +1139,10 @@ def _variable_assignment(self, key: str, expose: bool): suppressed_fallback = assignment else: winner = suppressed_fallback + # A unit added during the walk may have retired a candidate it + # already passed (a missing-unit loser that could now win), even + # after that candidate was checked: the caller walks again. + invalidated = self._units_seq != units_seq if pending: native = getattr(self.queue_exposure, "__func__", None) is \ Context.queue_exposure diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index d59a81f..c1ad91c 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -526,6 +526,70 @@ def set_units_after_exp_a(name, exposed_at=None): 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_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. From 5bcd83d56e3caa35cf64aedc5126afed5f024233 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 00:52:51 +0000 Subject: [PATCH 12/27] test: pin that re-setting a unit does not re-walk a shared key; clarify the changelog Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- test/test_shared_variable_keys.py | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2cf7bcd..cb29dd7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ ### 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) 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 anything; an experiment a concurrent `refresh` removed never wins the key; and the built-in queue accepts the winner together with its holdouts, so a concurrent close publishes both or neither. +- 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 any experiment (holdouts of the experiments it had already checked may still be published, once each); an experiment a concurrent `refresh` removed never wins the key; and the built-in queue accepts the winner together with its holdouts, so a concurrent close publishes both or neither. - 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/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index c1ad91c..d015e34 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -549,6 +549,24 @@ def set_units_before_exp_b(name, exposed_at=None): 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_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 From 4a9b0de88688add70720afe687433cb31c10212d Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 00:55:41 +0000 Subject: [PATCH 13/27] refactor: share native holdout acceptance and exposure logging; tidy comments Jervasion's optional suggestions: _expose and _expose_holdouts accept pinned arms and log accepted exposures through one helper each, and the comments it flagged as restating the next line are reworded or dropped. Co-Authored-By: Claude Opus 5.5 --- sdk/context.py | 55 +++++++++++++++---------------- test/test_context.py | 1 - test/test_shared_variable_keys.py | 6 ++-- 3 files changed, 29 insertions(+), 33 deletions(-) diff --git a/sdk/context.py b/sdk/context.py index ab11e82..0ac10cb 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -84,8 +84,8 @@ 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 - # Every holdout pinned on this assignment is exposed, so a variable - # read visiting it skips them (see Context._expose_holdouts). + # 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 @@ -1842,29 +1842,38 @@ def accept_assignment(): if not holdouts_first: accept_assignment() - for holdout, holdout_assignment in zip( - assignment.holdouts, assignment.holdout_assignments): - if offer_holdouts and holdout_assignment is not None: - # Named from this assignment's snapshot, like JS - # holdouts[i].data.name; the shared holdout assignment - # is not modified. - exposure = self._accept_exposure( - holdout_assignment, holdout.name, exposed_at) - if exposure is not None: - accepted.append(exposure) + if offer_holdouts: + self._accept_holdouts(assignment, exposed_at, accepted) if holdouts_first: accept_assignment() finally: self.event_lock.release_write() - for exposure in accepted: - self.log_event(EventType.EXPOSURE, exposure) - if offer_holdouts and assignment.holdout_assignments is not None: + 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): + # 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. + for holdout, holdout_assignment in zip( + assignment.holdouts, assignment.holdout_assignments): + if holdout_assignment is not None: + 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, offer_holdouts: bool = True): @@ -1996,23 +2005,13 @@ def _expose_holdouts(self, assignment: Assignment): try: self.event_lock.acquire_write() self.check_not_closed() - for holdout, holdout_assignment in zip( - assignment.holdouts, assignment.holdout_assignments): - if holdout_assignment is not None: - exposure = self._accept_exposure( - holdout_assignment, holdout.name, exposed_at) - if exposure is not None: - accepted.append(exposure) + self._accept_holdouts(assignment, exposed_at, accepted) finally: self.event_lock.release_write() - # Each arm is now exposed, by this read or an earlier one. assignment.holdouts_exposed = True assignment.holdouts_pending = False - for exposure in accepted: - self.log_event(EventType.EXPOSURE, exposure) - if accepted: - self.set_timeout() + self._log_exposures(accepted) @staticmethod def _holdouts_unexposed(assignment: Assignment): diff --git a/test/test_context.py b/test/test_context.py index 5342bad..0749407 100644 --- a/test/test_context.py +++ b/test/test_context.py @@ -1951,7 +1951,6 @@ def test_variable_value_skips_unassigned_experiment(self): self.assertEqual(expected, context.get_variable_value("banner.size", "d")) - # exp_a was only checked: it is not exposed. self.assertEqual(["exp_b"], [e.name for e in context.exposures]) context.set_override("exp_a", 1) diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index d015e34..25c7d30 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -58,7 +58,6 @@ def assert_winner(self, experiments, expected, exposed, **kwargs): self.assertEqual(expected, context.get_variable_value(KEY, "d")) self.assertEqual(exposed, self.names(context)) self.assertEqual(len(exposed), context.get_pending_count()) - # A second read exposes nothing more. self.assertEqual(expected, context.get_variable_value(KEY, "d")) self.assertEqual(exposed, self.names(context)) return context @@ -95,8 +94,8 @@ def test_winner_exposure_is_the_winning_assignment(self): self.exposure_tuples(context.exposures)) def test_winner_variant_without_the_key_returns_default(self): - # The unit gets exp_a's variant 1, which does not define the key: - # the default is returned and exp_b is never consulted or exposed. + # 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])], @@ -414,7 +413,6 @@ def queue_exposure(self, assignment): self.assertEqual(["holdout_b", "exp_a"], offered) self.assertEqual(["exp_a"], self.names(context)) self.assertTrue(context.get_assignment("exp_a").holdouts_pending) - # The next read offers the declined holdout again, and only it. context.get_variable_value(KEY, "d") self.assertEqual(["holdout_b", "exp_a", "holdout_b"], offered) self.assertEqual(["exp_a", "holdout_b"], self.names(context)) From 78511c0a0ae7a112e3baec4222e5ac86d43a8ac4 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 01:10:28 +0000 Subject: [PATCH 14/27] fix: re-walk a shared key after a refresh or unit change, peek included; no stale holdout offers CodeRabbit's findings on 5bcd83d: - peek_variable_value now walks the key again when a unit arrives or a refresh replaces the data during the walk. - A walk that will be repeated offers no holdouts, so a candidate the retry never visits publishes nothing. - The unit counter is checked again after the holdout pass, since a queue_exposure override may add a unit while being offered one. - A cached override of an experiment a refresh removed cannot win, even on the last walk. - README/CHANGELOG: a full-on experiment wins without its unit, and a default read can still publish visited holdouts. - Tests install holdout 12 where they claim it is not fired, and check the hook is offered h2 after h1 raises. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +- README.md | 6 +- sdk/context.py | 47 +++++---- test/test_shared_variable_keys.py | 154 +++++++++++++++++++++++++++++- 4 files changed, 188 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb29dd7..47c9620 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,11 +7,11 @@ - `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), 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. +- 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) 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 any experiment (holdouts of the experiments it had already checked may still be published, once each); an experiment a concurrent `refresh` removed never wins the key; and the built-in queue accepts the winner together with its holdouts, so a concurrent close publishes both or neither. +- 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 any experiment (holdouts of the experiments it had already checked may still be 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. - 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 db7f415..e8f6e9b 100644 --- a/README.md +++ b/README.md @@ -234,9 +234,9 @@ button_color = context.get_variable_value("button.color", "red") 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) get no exposure. -- 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), 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 nothing is exposed. +- 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 diff --git a/sdk/context.py b/sdk/context.py index 0ac10cb..29639dd 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -1070,11 +1070,14 @@ def peek_variable_value(self, key: str, default_value: object): def _variable_value(self, key: str, default_value: object, expose: bool, attempt: int = 1): - assignment, invalidated = self._variable_assignment(key, expose) retry = attempt < _MAX_EXPOSURE_ATTEMPTS - if expose and invalidated and retry: - # set_unit added a unit during the walk, so the key may resolve - # differently: walk it again before exposing anything. + assignment, invalidated = self._variable_assignment(key, expose, + retry) + if invalidated and 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) if expose and assignment is not None and \ @@ -1098,7 +1101,8 @@ def _expose_winner(self, assignment: Assignment): return self._expose(assignment, holdouts_first=True) return self._expose(assignment, offer_holdouts=False) - def _variable_assignment(self, key: str, expose: bool): + def _variable_assignment(self, key: str, expose: bool, + retry: bool = False): # 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 @@ -1112,19 +1116,25 @@ def _variable_assignment(self, key: str, expose: bool): # 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 and whether set_unit added a unit during - # the walk, which makes the caller walk again. + # Java. Returns the winner and whether set_unit added a unit or a + # refresh replaced the data during the walk, which makes the caller + # walk again; a walk that will be repeated offers no holdouts. units_seq = self._units_seq - experiments = Concurrency.get_rw( - self.data_lock, self.index_variables, key) or [] + try: + self.data_lock.acquire_read() + index = self.index + experiments = self.index_variables.get(key) or [] + finally: + self.data_lock.release_read() winner = None suppressed_fallback = None pending = None for experiment in list(experiments): assignment = self.get_assignment(experiment.data.name) # A refresh removed the indexed experiment after the index was - # read: its placeholder (id 0) must not win, even when overridden. - if assignment.id == 0 and \ + # 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 \ @@ -1139,11 +1149,12 @@ def _variable_assignment(self, key: str, expose: bool): suppressed_fallback = assignment else: winner = suppressed_fallback - # A unit added during the walk may have retired a candidate it - # already passed (a missing-unit loser that could now win), even - # after that candidate was checked: the caller walks again. - invalidated = self._units_seq != units_seq - if pending: + # 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 and retry): native = getattr(self.queue_exposure, "__func__", None) is \ Context.queue_exposure failure = None @@ -1158,6 +1169,10 @@ def _variable_assignment(self, key: str, expose: bool): failure = error 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 def peek_treatment(self, experiment_name: str): diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index 25c7d30..2bcf202 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -51,8 +51,10 @@ def setUp(self): def names(self, context): return [e.name for e in context.exposures] - def assert_winner(self, experiments, expected, exposed, **kwargs): - context = self.create_context(context_data(experiments), **kwargs) + 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")) @@ -99,7 +101,8 @@ def test_winner_variant_without_the_key_returns_default(self): context = self.assert_winner( [configs(1, "exp_a", {KEY: "a0"}, {"other": "x"}), assigned(2, "exp_b", holdout_ids=[12])], - "d", ["exp_a"]) + "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"]) @@ -425,8 +428,11 @@ def test_raising_hook_does_not_stop_the_other_holdouts(self): # 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") @@ -442,6 +448,7 @@ def queue_exposure(self, assignment): 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): @@ -565,6 +572,147 @@ def set_same_unit(name, exposed_at=None): 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_removed_experiment_cannot_win_on_the_last_walk(self): + # Every walk sees exp_a removed after it read the index and restored + # by the time it reaches exp_b, so the last walk cannot retry: its + # cached override must still not 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 + + def flip(name, exposed_at=None): + if name == "exp_a": + self.refresh(context, context_data([assigned(2, "exp_b")])) + else: + self.refresh(context, context_data( + [assigned(1, "exp_a"), assigned(2, "exp_b")])) + return get_assignment(name, exposed_at=exposed_at) + + context.get_assignment = flip + self.assertEqual("exp_b_treatment", + context.get_variable_value(KEY, "d")) + self.assertEqual(["exp_b"], self.names(context)) + 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 From e289cccd59f3d7157341aecf48832bb89420755e Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 01:49:11 +0000 Subject: [PATCH 15/27] fix: recompute an override placeholder once its experiment appears; cheaper index snapshot; pin the walk guards The 78511c0 gate: an override cached as an id-0 placeholder while its experiment was missing kept winning the key (default value, id-0 exposure) after a refresh added the experiment, and the reverse for a removed one. get_assignment now keeps a cached override only while the experiment's presence matches it. The index snapshot uses the data lock's write side, as Concurrency.get_rw does, recovering the warm-read cost. Tests pin the placeholder case, the lock-free warm read, the index re-check after a hook refreshes during the holdout pass, the snapshot under the lock and the last walk's loser holdout. Co-Authored-By: Claude Opus 5.5 --- sdk/context.py | 11 +++- test/test_shared_variable_keys.py | 106 ++++++++++++++++++++++++++---- 2 files changed, 104 insertions(+), 13 deletions(-) diff --git a/sdk/context.py b/sdk/context.py index 29639dd..0dfe9ab 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -1121,11 +1121,13 @@ def _variable_assignment(self, key: str, expose: bool, # walk again; a walk that will be repeated offers no holdouts. units_seq = self._units_seq try: - self.data_lock.acquire_read() + # 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_read() + self.data_lock.release_write() winner = None suppressed_fallback = None pending = None @@ -1429,8 +1431,13 @@ def get_assignment(self, experiment_name: str, exposed_at: int = None): pass elif experiment_name in self.overrides: override = self.overrides[experiment_name] + # Only while the experiment is still present, or still + # absent: a placeholder (id 0) cached while it was missing + # is recomputed once a refresh adds it, and a real one + # once a refresh removes it. if assignment.overridden and \ assignment.variant == override and \ + (experiment is None) == (assignment.id == 0) and \ (experiment is None or experiment.holdouts is assignment.holdouts or _holdout_set_matches(experiment, assignment)): diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index 2bcf202..a8531bc 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -691,27 +691,111 @@ def refresh_first(name, exposed_at=None): self.assertNotIn("exp_b", self.names(context)) def test_removed_experiment_cannot_win_on_the_last_walk(self): - # Every walk sees exp_a removed after it read the index and restored - # by the time it reaches exp_b, so the last walk cannot retry: its - # cached override must still not win. - context = self.create_context(context_data( - [assigned(1, "exp_a"), assigned(2, "exp_b")]), - overrides={"exp_a": 1}) + # Every walk sees exp_a removed right after its cached override was + # resolved and restored by the time it reaches exp_m, so the last + # walk cannot retry: the override must still not win, and the last + # walk still fires the holdout of the loser it visited. + 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": - self.refresh(context, context_data([assigned(2, "exp_b")])) - else: - self.refresh(context, context_data( - [assigned(1, "exp_a"), assigned(2, "exp_b")])) + 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("exp_b_treatment", context.get_variable_value(KEY, "d")) - self.assertEqual(["exp_b"], self.names(context)) + self.assertEqual(["holdout_m", "exp_b"], self.names(context)) + + 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) 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 From 8db380eb2010d4f5073e72bef03a77646e308488 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 02:15:25 +0000 Subject: [PATCH 16/27] fix: keep an exposed override across a refresh that removes its experiment The e289ccc gate: recomputing a cached override whenever its experiment was absent made get_treatment expose it again after a refresh removed the experiment, and an experiment with id 0 was never cached at all. The cache now drops an override only when the experiment is present with a different id (an id-0 placeholder once the experiment appears), which keeps 0.3.0 and JS behaviour on removal. Tests pin the removal case, the id-0 experiment and the index snapshot order; the CHANGELOG notes the placeholder re-exposure. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + sdk/context.py | 12 +++++---- test/test_shared_variable_keys.py | 45 +++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 47c9620..d08aaa3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ ### 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 any experiment (holdouts of the experiments it had already checked may still be 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. - 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/sdk/context.py b/sdk/context.py index 0dfe9ab..f6a9091 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -1431,13 +1431,15 @@ def get_assignment(self, experiment_name: str, exposed_at: int = None): pass elif experiment_name in self.overrides: override = self.overrides[experiment_name] - # Only while the experiment is still present, or still - # absent: a placeholder (id 0) cached while it was missing - # is recomputed once a refresh adds it, and a real one - # once a refresh removes it. + # Kept while its experiment is absent (as in JS, so a + # refresh removing it does not expose it again) or has + # the cached id: 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) == (assignment.id == 0) and \ + (experiment is None or + experiment.data.id == assignment.id) and \ (experiment is None or experiment.holdouts is assignment.holdouts or _holdout_set_matches(experiment, assignment)): diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index a8531bc..780be0c 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -796,6 +796,51 @@ def get(self, key, default=None): 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_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_set_unit_retiring_the_winner_before_exposure_walks_again(self): # exp_b wins while exp_a's unit is missing; the unit arrives as From fce6d230f3c5041ac713e17e427a737cdb8af293 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 02:33:17 +0000 Subject: [PATCH 17/27] fix: keep an exposed override when a refresh changes its experiment's id The 8db380e gate's P3: comparing the cached id with the payload id exposed an override again when a refresh re-identified its experiment (main, 0.3.0 and JS keep it). Only an id-0 placeholder cached while the experiment was missing is now recomputed. A test pins the id change. Co-Authored-By: Claude Opus 5.5 --- sdk/context.py | 10 +++++----- test/test_shared_variable_keys.py | 12 ++++++++++++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/sdk/context.py b/sdk/context.py index f6a9091..ef156de 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -1431,15 +1431,15 @@ def get_assignment(self, experiment_name: str, exposed_at: int = None): pass elif experiment_name in self.overrides: override = self.overrides[experiment_name] - # Kept while its experiment is absent (as in JS, so a - # refresh removing it does not expose it again) or has - # the cached id: a placeholder (id 0) cached while the + # 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 - experiment.data.id == assignment.id) 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)): diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index 780be0c..4e57335 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -833,6 +833,18 @@ def test_exposed_override_is_not_exposed_again_after_its_removal(self): [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_of_an_experiment_with_id_0_is_exposed_once(self): context = self.create_context(context_data([assigned(0, "exp_a")]), overrides={"exp_a": 1}) From 2f3023ed5a8501e54bf3c435c2abf9613e05b6f4 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 02:50:31 +0000 Subject: [PATCH 18/27] fix: give a kept override its experiment's variables once the experiment appears The fce6d23 gate's P3: an override cached while its experiment was missing, kept when a refresh adds the experiment with id 0, had no variables, so it won the key and returned the default. It now takes the variables from the payload, as JS does on refresh. A test pins it. Co-Authored-By: Claude Opus 5.5 --- sdk/context.py | 9 +++++++++ test/test_shared_variable_keys.py | 15 +++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/sdk/context.py b/sdk/context.py index ef156de..dd2e0a5 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -1443,6 +1443,15 @@ def get_assignment(self, experiment_name: str, exposed_at: int = None): (experiment is None or experiment.holdouts is assignment.holdouts or _holdout_set_matches(experiment, assignment)): + if assignment.variables is None and \ + experiment is not None and \ + 0 <= assignment.variant < \ + len(experiment.data.variants): + # Kept from before the experiment was known (an + # id-0 experiment): take its variables now, as + # JS does on refresh. + assignment.variables = \ + experiment.variables[assignment.variant] return assignment elif experiment is None: if assignment.assigned is False and \ diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index 4e57335..4589117 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -845,6 +845,21 @@ def test_exposed_override_is_not_exposed_again_when_its_id_changes(self): [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_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}) From 6d6f70c50346bc9769192e342b4488fe0dfb0a7e Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 03:10:29 +0000 Subject: [PATCH 19/27] fix: fill a kept override's variables only for the same experiment; pin the fill guards The 2f3023e gate: the variables fill ran for any kept override without variables, unlike JS followArm, so an override to a missing variant of a re-identified experiment took the new variant's value. It now also requires the cached id to match. Tests pin each guard: variables kept across a config change, a negative override never reading from the end of the variants, and the re-identified experiment. Co-Authored-By: Claude Opus 5.5 --- sdk/context.py | 8 ++++--- test/test_shared_variable_keys.py | 35 +++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/sdk/context.py b/sdk/context.py index dd2e0a5..652ed03 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -1445,11 +1445,13 @@ def get_assignment(self, experiment_name: str, exposed_at: int = None): _holdout_set_matches(experiment, 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): - # Kept from before the experiment was known (an - # id-0 experiment): take its variables now, as - # JS does on refresh. + # Kept without variables (cached before an id-0 + # experiment was known, or overridden to a variant + # it did not have yet) for the same experiment: + # take its variables now, as JS followArm does. assignment.variables = \ experiment.variables[assignment.variant] return assignment diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index 4589117..30d82e8 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -860,6 +860,41 @@ def test_override_kept_from_before_an_id_0_experiment_gets_its_value( 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_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}) From 80d68ec3e12f1296c3131c95b52c35c5aa149ade Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 03:27:48 +0000 Subject: [PATCH 20/27] test: pin that a kept override takes a variant a refresh adds to the same experiment Co-Authored-By: Claude Opus 5.5 --- test/test_shared_variable_keys.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index 30d82e8..d36411c 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -881,6 +881,21 @@ def test_negative_override_never_reads_a_variant_from_the_end(self): 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 From 261281dfaa162863e0225bdf12558eacdad6224e Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 03:50:22 +0000 Subject: [PATCH 21/27] fix: coherent final shared-key walk, per-read holdout offers, shared holdouts with the winner, atomic override fill CodeRabbit's findings on 80d68ec: - A final attempt that still sees the data or units change returns the default and exposes nothing, instead of a winner no single payload gives (e.g. a same-name experiment no longer defining the key). - Arms offered to a queue_exposure override are tracked per public read, so a declined arm is not offered again by a retry in the same read; the next read offers it again. - A holdout arm a loser shares with the winner is accepted in the winner's section, so a close started from the logger on it cannot publish it without the winner; losers whose arms were deferred are marked exposed afterwards so warm reads still skip them. - A kept override's variables are filled under the context write lock, re-reading the experiment under data_lock, so a reader that checked the cache before a refresh cannot store the old payload's variables. - CHANGELOG: the no-repeat guarantee for restored overrides is qualified, and the exhausted-retry rule is stated. Each guard has a test that fails without it. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +- sdk/context.py | 133 ++++++++++++++++++++++-------- test/test_shared_variable_keys.py | 126 ++++++++++++++++++++++++++-- 3 files changed, 219 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d08aaa3..c1c9de1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,8 +11,8 @@ ### 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 any experiment (holdouts of the experiments it had already checked may still be 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. +- 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 anything, and if it never sees one consistent state within its attempts it returns the default and exposes nothing; 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 `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/sdk/context.py b/sdk/context.py index 652ed03..d7d2ff8 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -1069,23 +1069,39 @@ 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): + attempt: int = 1, offered=None): retry = attempt < _MAX_EXPOSURE_ATTEMPTS - assignment, invalidated = self._variable_assignment(key, expose, - retry) - if invalidated and 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) + 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) and retry: # set_unit retired the winner in between: walk it again. return self._variable_value(key, default_value, expose, - attempt + 1) + attempt + 1, offered) + 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] @@ -1102,7 +1118,7 @@ def _expose_winner(self, assignment: Assignment): return self._expose(assignment, offer_holdouts=False) def _variable_assignment(self, key: str, expose: bool, - retry: bool = False): + 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 @@ -1116,9 +1132,11 @@ def _variable_assignment(self, key: str, expose: bool, # 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 and whether set_unit added a unit or a - # refresh replaced the data during the walk, which makes the caller - # walk again; a walk that will be repeated offers no holdouts. + # 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 @@ -1131,6 +1149,7 @@ def _variable_assignment(self, key: str, expose: bool, winner = None suppressed_fallback = None pending = None + deferred = () for experiment in list(experiments): assignment = self.get_assignment(experiment.data.name) # A refresh removed the indexed experiment after the index was @@ -1156,26 +1175,40 @@ def _variable_assignment(self, key: str, expose: bool, # 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 and retry): + 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 and \ + not winner.exposed.value: + # 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. Walk order is kept: those arms are + # accepted in the winner's section, before its own exposure. + staged = {id(arm) for arm in winner.holdout_assignments + if arm is not None} + else: + staged = () failure = None for candidate in pending: if native and candidate is winner: - # Accepted with the winner, see _expose_winner. continue try: - self._expose_holdouts(candidate) + 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 + return winner, invalidated, deferred def peek_treatment(self, experiment_name: str): self.check_ready(True) @@ -1416,6 +1449,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() @@ -1448,13 +1482,10 @@ def get_assignment(self, experiment_name: str, exposed_at: int = None): assignment.id == experiment.data.id and \ 0 <= assignment.variant < \ len(experiment.data.variants): - # Kept without variables (cached before an id-0 - # experiment was known, or overridden to a variant - # it did not have yet) for the same experiment: - # take its variables now, as JS followArm does. - assignment.variables = \ - experiment.variables[assignment.variant] - return assignment + # 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: @@ -1476,6 +1507,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 @@ -1891,13 +1943,15 @@ def accept_assignment(): return True def _accept_holdouts(self, assignment: Assignment, exposed_at, - accepted: list): + 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. + # 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: + 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: @@ -1967,7 +2021,7 @@ def _expose_through_hook(self, assignment: Assignment, return True def _offer_holdouts_through_hook(self, assignment: Assignment, - exposed_at): + 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 @@ -1985,10 +2039,14 @@ def _offer_holdouts_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 + id(holdout_assignment) in offered): finished = False continue holdout_assignment.hook_pending = True + if offered is not None: + offered.add(id(holdout_assignment)) finally: self.event_lock.release_write() try: @@ -2010,7 +2068,8 @@ def _offer_holdouts_through_hook(self, assignment: Assignment, raise failure return finished - def _expose_holdouts(self, assignment: Assignment): + def _expose_holdouts(self, assignment: Assignment, offered=None, + staged=()): """Expose the holdouts pinned on a variable-key candidate, not the candidate itself (Java triggerApplicableHoldoutExposures). @@ -2030,7 +2089,8 @@ def _expose_holdouts(self, assignment: Assignment): 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) + self._offer_holdouts_through_hook(assignment, exposed_at, + offered) if not self._holdouts_unexposed(assignment): assignment.holdouts_exposed = True assignment.holdouts_pending = False @@ -2040,12 +2100,13 @@ def _expose_holdouts(self, assignment: Assignment): try: self.event_lock.acquire_write() self.check_not_closed() - self._accept_holdouts(assignment, exposed_at, accepted) + self._accept_holdouts(assignment, exposed_at, accepted, staged) finally: self.event_lock.release_write() - assignment.holdouts_exposed = True - assignment.holdouts_pending = False + if not staged or not self._holdouts_unexposed(assignment): + assignment.holdouts_exposed = True + assignment.holdouts_pending = False self._log_exposures(accepted) @staticmethod diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index d36411c..393b502 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -690,11 +690,12 @@ def refresh_first(name, exposed_at=None): getattr(context, read)(KEY, "d")) self.assertNotIn("exp_b", self.names(context)) - def test_removed_experiment_cannot_win_on_the_last_walk(self): + 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, so the last - # walk cannot retry: the override must still not win, and the last - # walk still fires the holdout of the loser it visited. + # 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")] @@ -713,9 +714,11 @@ def flip(name, exposed_at=None): return get_assignment(name, exposed_at=exposed_at) context.get_assignment = flip - self.assertEqual("exp_b_treatment", + 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")) - self.assertEqual(["holdout_m", "exp_b"], self.names(context)) def test_override_placeholder_cached_before_a_refresh_adds_the_experiment( self): @@ -919,6 +922,117 @@ def test_override_of_an_experiment_with_id_0_is_exposed_once(self): 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_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 From edb405db03fa3009c19e07e6d95a250a5c19d548 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 04:27:21 +0000 Subject: [PATCH 22/27] fix: default when the last attempt's winner is retired; offer set only for hooks; pin fill and deferral guards The 261281d gate: - A read whose winner set_unit retired on every attempt returned the unexposed winner's value; it now returns the default, as the CHANGELOG promises for a read that never sees one state. - The per-read offer set is allocated only when queue_exposure is overridden, recovering the warm-read cost. - The redundant winner skip and staging condition are removed (no observable effect, flagged as surviving mutants); the staging comment now says holdout order within a read is not guaranteed. - Tests pin the fill's id re-check, a deferred loser keeping its shared arm pending when the winner's exposure fails, the retired-winner default and the offer-set allocation. Co-Authored-By: Claude Opus 5.5 --- sdk/context.py | 28 ++++++---- test/test_shared_variable_keys.py | 89 +++++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+), 11 deletions(-) diff --git a/sdk/context.py b/sdk/context.py index d7d2ff8..1156834 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -1071,7 +1071,9 @@ def peek_variable_value(self, key: str, default_value: object): def _variable_value(self, key: str, default_value: object, expose: bool, attempt: int = 1, offered=None): retry = attempt < _MAX_EXPOSURE_ATTEMPTS - if offered is None and expose: + if offered is None and expose and \ + getattr(self.queue_exposure, "__func__", None) is not \ + Context.queue_exposure: # 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). @@ -1092,10 +1094,15 @@ def _variable_value(self, key: str, default_value: object, expose: bool, return default_value if expose and assignment is not None and \ not assignment.exposed.value and \ - not self._expose_winner(assignment) and retry: - # set_unit retired the winner in between: walk it again. - return self._variable_value(key, default_value, expose, - attempt + 1, offered) + 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. @@ -1179,21 +1186,20 @@ def _variable_assignment(self, key: str, expose: bool, 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 and \ - not winner.exposed.value: + 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. Walk order is kept: those arms are - # accepted in the winner's section, before its own exposure. + # 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: - if native and candidate is winner: - continue try: self._expose_holdouts(candidate, offered, staged) except Exception as error: diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index 393b502..4136887 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -1033,6 +1033,95 @@ def refresh_before_the_fill(): 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_built_in_queue_tracks_no_offers(self): + # The per-read offer set is only for a queue_exposure override; the + # built-in queue accepts arms once under event_lock instead. + 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)])) + seen = [] + walk = context._variable_assignment + context._variable_assignment = \ + lambda *args: seen.append(args[3]) or walk(*args) + context.get_variable_value(KEY, "d") + self.assertEqual([None], seen) + 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 From 91dd0394490f4bc3443257bb69712275291fc453 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 04:57:08 +0000 Subject: [PATCH 23/27] fix: judge a queue_exposure override by the assignment's state, not its return value The edb405d gate: without holdouts, _expose took a hook's False return as a set_unit retirement, so get_variable_value returned the default on the last attempt and the hook was called three times (main did the same for get_treatment; 0.3.0 called it once). Like _expose_through_hook, an override is now judged by whether the assignment is exposed or retired. The offer-set guard is dropped (it saved nothing measurable). Tests pin a declining hook and a hook that sees the winner retired. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + sdk/context.py | 13 ++++--- test/test_shared_variable_keys.py | 56 ++++++++++++++++++++++++------- 3 files changed, 54 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c1c9de1..069ee30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ - 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 anything, and if it never sees one consistent state within its attempts it returns the default and exposes nothing; 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 `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/sdk/context.py b/sdk/context.py index 1156834..a5cc7d8 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -1071,9 +1071,7 @@ def peek_variable_value(self, key: str, default_value: object): def _variable_value(self, key: str, default_value: object, expose: bool, attempt: int = 1, offered=None): retry = attempt < _MAX_EXPOSURE_ATTEMPTS - if offered is None and expose and \ - getattr(self.queue_exposure, "__func__", None) is not \ - Context.queue_exposure: + 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). @@ -1910,7 +1908,14 @@ def _expose(self, assignment: Assignment, offer_holdouts: bool = True, (_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 + queued = self.queue_exposure(assignment) + if getattr(self.queue_exposure, "__func__", None) is not \ + Context.queue_exposure: + # Judged by the state, like _expose_through_hook: an + # override's return value (v0.2.4 hooks may return False to + # decline) is not a set_unit retirement. + return assignment.exposed.value or not assignment.retired + return queued is not False if getattr(self.queue_exposure, "__func__", None) is not \ Context.queue_exposure: return self._expose_through_hook(assignment, offer_holdouts) diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index 4136887..d09873c 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -1108,19 +1108,51 @@ def retire_first(assignment): self.assertEqual(["exp_b", "exp_b", "exp_b"], attempts) self.assertEqual([], self.names(context)) - def test_built_in_queue_tracks_no_offers(self): - # The per-read offer set is only for a queue_exposure override; the - # built-in queue accepts arms once under event_lock instead. + 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", holdout_ids=[12]), - assigned(2, "exp_b")], - [holdout(12, "holdout_b", HOLDOUT_B_SEEDS)])) - seen = [] - walk = context._variable_assignment - context._variable_assignment = \ - lambda *args: seen.append(args[3]) or walk(*args) - context.get_variable_value(KEY, "d") - self.assertEqual([None], seen) + [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_set_unit_retiring_the_winner_before_exposure_walks_again(self): # exp_b wins while exp_a's unit is missing; the unit arrives as From df79187cdfd9aebbce48c9757c9c985705d45174 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 05:25:06 +0000 Subject: [PATCH 24/27] fix: never hand a queue_exposure override an assignment set_unit already retired The 91dd039 gate: for an experiment without holdouts, _expose called the hook before checking retirement, so a set_unit landing between resolving and exposing made one get_treatment send two exposures to the hook. Like _expose_through_hook, the retired flag is checked under event_lock before the call. Tests pin that the hook is never handed a retired assignment, and that get_treatment judges a hook by the assignment's state when the hook itself adds the unit. Co-Authored-By: Claude Opus 5.5 --- sdk/context.py | 21 ++++++++----- test/test_shared_variable_keys.py | 52 +++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 7 deletions(-) diff --git a/sdk/context.py b/sdk/context.py index a5cc7d8..79eb8ed 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -1908,14 +1908,21 @@ def _expose(self, assignment: Assignment, offer_holdouts: bool = True, (_expose_holdouts) and a declined one is not offered twice in a read. """ if assignment.holdout_assignments is None: - queued = self.queue_exposure(assignment) - if getattr(self.queue_exposure, "__func__", None) is not \ + if getattr(self.queue_exposure, "__func__", None) is \ Context.queue_exposure: - # Judged by the state, like _expose_through_hook: an - # override's return value (v0.2.4 hooks may return False to - # decline) is not a set_unit retirement. - return assignment.exposed.value or not assignment.retired - return queued is not False + 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, offer_holdouts) diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index d09873c..b66bfaf 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -1154,6 +1154,58 @@ def queue_exposure(self, assignment): 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_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 From 17207aef539b75bef57c3a01f9444f25e2ecf8ae Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 05:42:02 +0000 Subject: [PATCH 25/27] docs: note the warm variable-read cost of the lifecycle checks Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 069ee30..376a9e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ - 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 anything, and if it never sees one consistent state within its attempts it returns the default and exposes nothing; 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. From 4d5e509319aec07823c1c0897b0984b0b2083a4a Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 05:57:15 +0000 Subject: [PATCH 26/27] fix: track offered holdout arms by object; qualify the changelog's no-exposure wording CodeRabbit on 17207ae: - The per-read offer set kept id()s; an arm released by a refresh could have its id reused by a new arm the hook never received, which would then be skipped. It now keeps the arm objects (alive for the read). - CHANGELOG: a read returning the default exposes no winner, but holdouts of experiments it had already checked may already be published (the accepted visited-candidate rule). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- sdk/context.py | 7 +++++-- test/test_shared_variable_keys.py | 24 ++++++++++++++++++++++++ 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 376a9e5..1c2f98a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ ### 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 anything, and if it never sees one consistent state within its attempts it returns the default and exposes nothing; 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. +- 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. diff --git a/sdk/context.py b/sdk/context.py index 79eb8ed..9df5e7a 100644 --- a/sdk/context.py +++ b/sdk/context.py @@ -2059,12 +2059,15 @@ def _offer_holdouts_through_hook(self, assignment: Assignment, continue if holdout_assignment.hook_pending or ( offered is not None and - id(holdout_assignment) in offered): + holdout_assignment in offered): finished = False continue holdout_assignment.hook_pending = True if offered is not None: - offered.add(id(holdout_assignment)) + # 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: diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index b66bfaf..29f82ce 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -1206,6 +1206,30 @@ def set_unit_after_first(name, exposed_at=None): self.assertEqual([(False, True)], handed) self.assertEqual(1, context.get_pending_count()) + def test_offered_arms_are_tracked_by_object_not_id(self): + # The per-read set keeps the offered arm itself: an arm a refresh + # creates must be offered even if it would reuse a released arm's + # id. Simulated by an arm whose id() collides with an offered one. + 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 From 7ddd5dd4c7e43f55f60106c30126508718378501 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 06:28:27 +0000 Subject: [PATCH 27/27] test: say the offered-arm test pins storage, not a reachable race Co-Authored-By: Claude Opus 5.5 --- test/test_shared_variable_keys.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/test/test_shared_variable_keys.py b/test/test_shared_variable_keys.py index 29f82ce..deb0109 100644 --- a/test/test_shared_variable_keys.py +++ b/test/test_shared_variable_keys.py @@ -1207,9 +1207,11 @@ def set_unit_after_first(name, exposed_at=None): self.assertEqual(1, context.get_pending_count()) def test_offered_arms_are_tracked_by_object_not_id(self): - # The per-read set keeps the offered arm itself: an arm a refresh - # creates must be offered even if it would reuse a released arm's - # id. Simulated by an arm whose id() collides with an offered one. + # 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 = []