From 116d23ad80c7741acdf3c14638601a5a884c8d34 Mon Sep 17 00:00:00 2001 From: Farhan Anjum Date: Wed, 15 Oct 2025 15:01:25 +0600 Subject: [PATCH 01/32] [FSSDK-11901] Fix concurrency bug in cmab service (#462) * Update: Implement locking mechanism for CMAB service to enhance concurrency * Update: Refactor get_decision method * update: type checking fix * Update: Remove Python 3.8 from testing matrix in CI workflow --- .github/workflows/python.yml | 4 -- optimizely/bucketer.py | 2 +- optimizely/cmab/cmab_service.py | 18 +++++++++ .../decision/optimizely_decide_option.py | 2 +- .../decision/optimizely_decision_message.py | 2 +- optimizely/entities.py | 2 +- optimizely/event/event_factory.py | 2 +- optimizely/event/event_processor.py | 2 +- optimizely/event/log_event.py | 2 +- optimizely/event/user_event.py | 2 +- optimizely/event_builder.py | 2 +- optimizely/event_dispatcher.py | 2 +- optimizely/helpers/condition.py | 2 +- optimizely/helpers/enums.py | 2 +- optimizely/helpers/event_tag_utils.py | 2 +- optimizely/logger.py | 2 +- optimizely/notification_center.py | 2 +- optimizely/odp/lru_cache.py | 2 +- optimizely/odp/optimizely_odp_option.py | 2 +- optimizely/project_config.py | 2 +- optimizely/user_profile.py | 2 +- tests/test_cmab_service.py | 40 ++++++++++++++++++- 22 files changed, 76 insertions(+), 24 deletions(-) diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 0699f84c0..6baa2c09c 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -65,10 +65,8 @@ jobs: fail-fast: false matrix: python-version: - - "pypy-3.8" - "pypy-3.9" - "pypy-3.10" - - "3.8" - "3.9" - "3.10" - "3.11" @@ -93,10 +91,8 @@ jobs: fail-fast: false matrix: python-version: - - "pypy-3.8" - "pypy-3.9" - "pypy-3.10" - - "3.8" - "3.9" - "3.10" - "3.11" diff --git a/optimizely/bucketer.py b/optimizely/bucketer.py index 1bd7ff527..a6e8323d6 100644 --- a/optimizely/bucketer.py +++ b/optimizely/bucketer.py @@ -22,7 +22,7 @@ if version_info < (3, 8): from typing_extensions import Final else: - from typing import Final # type: ignore + from typing import Final if TYPE_CHECKING: diff --git a/optimizely/cmab/cmab_service.py b/optimizely/cmab/cmab_service.py index a7c4b69bc..82c2c2061 100644 --- a/optimizely/cmab/cmab_service.py +++ b/optimizely/cmab/cmab_service.py @@ -13,6 +13,7 @@ import uuid import json import hashlib +import threading from typing import Optional, List, TypedDict from optimizely.cmab.cmab_client import DefaultCmabClient @@ -21,6 +22,8 @@ from optimizely.project_config import ProjectConfig from optimizely.decision.optimizely_decide_option import OptimizelyDecideOption from optimizely import logger as _logging +from optimizely.lib import pymmh3 as mmh3 +NUM_LOCK_STRIPES = 1000 class CmabDecision(TypedDict): @@ -52,10 +55,25 @@ def __init__(self, cmab_cache: LRUCache[str, CmabCacheValue], self.cmab_cache = cmab_cache self.cmab_client = cmab_client self.logger = logger + self.locks = [threading.Lock() for _ in range(NUM_LOCK_STRIPES)] + + def _get_lock_index(self, user_id: str, rule_id: str) -> int: + """Calculate the lock index for a given user and rule combination.""" + # Create a hash of user_id + rule_id for consistent lock selection + hash_input = f"{user_id}{rule_id}" + hash_value = mmh3.hash(hash_input, seed=0) & 0xFFFFFFFF # Convert to unsigned + return hash_value % NUM_LOCK_STRIPES def get_decision(self, project_config: ProjectConfig, user_context: OptimizelyUserContext, rule_id: str, options: List[str]) -> CmabDecision: + lock_index = self._get_lock_index(user_context.user_id, rule_id) + with self.locks[lock_index]: + return self._get_decision(project_config, user_context, rule_id, options) + + def _get_decision(self, project_config: ProjectConfig, user_context: OptimizelyUserContext, + rule_id: str, options: List[str]) -> CmabDecision: + filtered_attributes = self._filter_attributes(project_config, user_context, rule_id) if OptimizelyDecideOption.IGNORE_CMAB_CACHE in options: diff --git a/optimizely/decision/optimizely_decide_option.py b/optimizely/decision/optimizely_decide_option.py index 8cffcfec1..0443ddef4 100644 --- a/optimizely/decision/optimizely_decide_option.py +++ b/optimizely/decision/optimizely_decide_option.py @@ -16,7 +16,7 @@ if version_info < (3, 8): from typing_extensions import Final else: - from typing import Final # type: ignore + from typing import Final class OptimizelyDecideOption: diff --git a/optimizely/decision/optimizely_decision_message.py b/optimizely/decision/optimizely_decision_message.py index 20231ea5b..c61783225 100644 --- a/optimizely/decision/optimizely_decision_message.py +++ b/optimizely/decision/optimizely_decision_message.py @@ -16,7 +16,7 @@ if version_info < (3, 8): from typing_extensions import Final else: - from typing import Final # type: ignore + from typing import Final class OptimizelyDecisionMessage: diff --git a/optimizely/entities.py b/optimizely/entities.py index 7d2576565..83488bdf6 100644 --- a/optimizely/entities.py +++ b/optimizely/entities.py @@ -17,7 +17,7 @@ if version_info < (3, 8): from typing_extensions import Final else: - from typing import Final # type: ignore + from typing import Final if TYPE_CHECKING: diff --git a/optimizely/event/event_factory.py b/optimizely/event/event_factory.py index c872fb178..48b3a5ccf 100644 --- a/optimizely/event/event_factory.py +++ b/optimizely/event/event_factory.py @@ -25,7 +25,7 @@ if version_info < (3, 8): from typing_extensions import Final else: - from typing import Final # type: ignore + from typing import Final if TYPE_CHECKING: # prevent circular dependenacy by skipping import at runtime diff --git a/optimizely/event/event_processor.py b/optimizely/event/event_processor.py index 05f5e078b..4fba29ebd 100644 --- a/optimizely/event/event_processor.py +++ b/optimizely/event/event_processor.py @@ -34,7 +34,7 @@ if version_info < (3, 8): from typing_extensions import Final else: - from typing import Final # type: ignore + from typing import Final class BaseEventProcessor(ABC): diff --git a/optimizely/event/log_event.py b/optimizely/event/log_event.py index 7c0beeb62..49c344dd8 100644 --- a/optimizely/event/log_event.py +++ b/optimizely/event/log_event.py @@ -20,7 +20,7 @@ if version_info < (3, 8): from typing_extensions import Literal else: - from typing import Literal # type: ignore + from typing import Literal class LogEvent(event_builder.Event): diff --git a/optimizely/event/user_event.py b/optimizely/event/user_event.py index e257647cb..c1152161d 100644 --- a/optimizely/event/user_event.py +++ b/optimizely/event/user_event.py @@ -22,7 +22,7 @@ if version_info < (3, 8): from typing_extensions import Final else: - from typing import Final # type: ignore + from typing import Final if TYPE_CHECKING: diff --git a/optimizely/event_builder.py b/optimizely/event_builder.py index 90678830d..e9c9fd44a 100644 --- a/optimizely/event_builder.py +++ b/optimizely/event_builder.py @@ -25,7 +25,7 @@ if version_info < (3, 8): from typing_extensions import Final, Literal else: - from typing import Final, Literal # type: ignore + from typing import Final, Literal if TYPE_CHECKING: # prevent circular dependenacy by skipping import at runtime diff --git a/optimizely/event_dispatcher.py b/optimizely/event_dispatcher.py index 767fbb7dd..55209dc8e 100644 --- a/optimizely/event_dispatcher.py +++ b/optimizely/event_dispatcher.py @@ -26,7 +26,7 @@ if version_info < (3, 8): from typing_extensions import Protocol else: - from typing import Protocol # type: ignore + from typing import Protocol class CustomEventDispatcher(Protocol): diff --git a/optimizely/helpers/condition.py b/optimizely/helpers/condition.py index 58000a909..40338b407 100644 --- a/optimizely/helpers/condition.py +++ b/optimizely/helpers/condition.py @@ -32,7 +32,7 @@ if version_info < (3, 8): from typing_extensions import Literal, Final else: - from typing import Literal, Final # type: ignore + from typing import Literal, Final class ConditionOperatorTypes: diff --git a/optimizely/helpers/enums.py b/optimizely/helpers/enums.py index e3acafef2..4630491c4 100644 --- a/optimizely/helpers/enums.py +++ b/optimizely/helpers/enums.py @@ -17,7 +17,7 @@ if version_info < (3, 8): from typing_extensions import Final else: - from typing import Final # type: ignore + from typing import Final class CommonAudienceEvaluationLogs: diff --git a/optimizely/helpers/event_tag_utils.py b/optimizely/helpers/event_tag_utils.py index cb577950b..ad90cc132 100644 --- a/optimizely/helpers/event_tag_utils.py +++ b/optimizely/helpers/event_tag_utils.py @@ -21,7 +21,7 @@ if version_info < (3, 8): from typing_extensions import Final else: - from typing import Final # type: ignore + from typing import Final if TYPE_CHECKING: diff --git a/optimizely/logger.py b/optimizely/logger.py index 33d3660c9..42f879de6 100644 --- a/optimizely/logger.py +++ b/optimizely/logger.py @@ -20,7 +20,7 @@ if version_info < (3, 8): from typing_extensions import Final else: - from typing import Final # type: ignore + from typing import Final _DEFAULT_LOG_FORMAT: Final = '%(levelname)-8s %(asctime)s %(filename)s:%(lineno)s:%(message)s' diff --git a/optimizely/notification_center.py b/optimizely/notification_center.py index 322a58628..3d0b0cba3 100644 --- a/optimizely/notification_center.py +++ b/optimizely/notification_center.py @@ -20,7 +20,7 @@ if version_info < (3, 8): from typing_extensions import Final else: - from typing import Final # type: ignore + from typing import Final NOTIFICATION_TYPES: Final = tuple( diff --git a/optimizely/odp/lru_cache.py b/optimizely/odp/lru_cache.py index 073973e64..64337dadd 100644 --- a/optimizely/odp/lru_cache.py +++ b/optimizely/odp/lru_cache.py @@ -22,7 +22,7 @@ if version_info < (3, 8): from typing_extensions import Protocol else: - from typing import Protocol # type: ignore + from typing import Protocol # generic type definitions for LRUCache parameters K = TypeVar('K', bound=Hashable, contravariant=True) diff --git a/optimizely/odp/optimizely_odp_option.py b/optimizely/odp/optimizely_odp_option.py index ce6eaf006..94e1e90e4 100644 --- a/optimizely/odp/optimizely_odp_option.py +++ b/optimizely/odp/optimizely_odp_option.py @@ -16,7 +16,7 @@ if version_info < (3, 8): from typing_extensions import Final else: - from typing import Final # type: ignore + from typing import Final class OptimizelyOdpOption: diff --git a/optimizely/project_config.py b/optimizely/project_config.py index 446d1e2fa..89c9b48b6 100644 --- a/optimizely/project_config.py +++ b/optimizely/project_config.py @@ -24,7 +24,7 @@ if version_info < (3, 8): from typing_extensions import Final else: - from typing import Final # type: ignore + from typing import Final if TYPE_CHECKING: # prevent circular dependenacy by skipping import at runtime diff --git a/optimizely/user_profile.py b/optimizely/user_profile.py index f5ded013e..e3a56195c 100644 --- a/optimizely/user_profile.py +++ b/optimizely/user_profile.py @@ -19,7 +19,7 @@ if version_info < (3, 8): from typing_extensions import Final else: - from typing import Final, TYPE_CHECKING # type: ignore + from typing import Final, TYPE_CHECKING if TYPE_CHECKING: # prevent circular dependenacy by skipping import at runtime diff --git a/tests/test_cmab_service.py b/tests/test_cmab_service.py index 0b3c593a5..5aede6954 100644 --- a/tests/test_cmab_service.py +++ b/tests/test_cmab_service.py @@ -12,7 +12,7 @@ # limitations under the License. import unittest from unittest.mock import MagicMock -from optimizely.cmab.cmab_service import DefaultCmabService +from optimizely.cmab.cmab_service import DefaultCmabService, NUM_LOCK_STRIPES from optimizely.optimizely_user_context import OptimizelyUserContext from optimizely.decision.optimizely_decide_option import OptimizelyDecideOption from optimizely.odp.lru_cache import LRUCache @@ -185,3 +185,41 @@ def test_only_cmab_attributes_passed_to_client(self): {"age": 25, "location": "USA"}, decision["cmab_uuid"] ) + + def test_same_user_rule_combination_uses_consistent_lock(self): + """Verifies that the same user/rule combination always uses the same lock index""" + user_id = "test_user" + rule_id = "test_rule" + + # Get lock index multiple times + index1 = self.cmab_service._get_lock_index(user_id, rule_id) + index2 = self.cmab_service._get_lock_index(user_id, rule_id) + index3 = self.cmab_service._get_lock_index(user_id, rule_id) + + # All should be the same + self.assertEqual(index1, index2, "Same user/rule should always use same lock") + self.assertEqual(index2, index3, "Same user/rule should always use same lock") + + def test_lock_striping_distribution(self): + """Verifies that different user/rule combinations use different locks to allow for better concurrency""" + test_cases = [ + ("user1", "rule1"), + ("user2", "rule1"), + ("user1", "rule2"), + ("user3", "rule3"), + ("user4", "rule4"), + ] + + lock_indices = set() + for user_id, rule_id in test_cases: + index = self.cmab_service._get_lock_index(user_id, rule_id) + + # Verify index is within expected range + self.assertGreaterEqual(index, 0, "Lock index should be non-negative") + self.assertLess(index, NUM_LOCK_STRIPES, "Lock index should be less than NUM_LOCK_STRIPES") + + lock_indices.add(index) + + # We should have multiple different lock indices (though not necessarily all unique due to hash collisions) + self.assertGreater(len(lock_indices), 1, + "Different user/rule combinations should generally use different locks") From 9b4af2fd5339027c21e5edc7f6538fecf81f33e2 Mon Sep 17 00:00:00 2001 From: esrakartalOpt <102107327+esrakartalOpt@users.noreply.github.com> Date: Mon, 3 Nov 2025 08:05:29 -0600 Subject: [PATCH 02/32] [FSSDK-11569][FSSDK-11570] Python: Holdout Project Config update (#464) * [FSSDK-11569][FSSDK-11570] Python: Holdout Project Config update * Fix lint issues * Fix the python issue * Fix the python issue on typing.txt --- optimizely/project_config.py | 91 ++++++++++++++++++++ requirements/core.txt | 1 + requirements/typing.txt | 3 +- tests/test_config.py | 159 +++++++++++++++++++++++++++++++++++ 4 files changed, 253 insertions(+), 1 deletion(-) diff --git a/optimizely/project_config.py b/optimizely/project_config.py index 89c9b48b6..1e813462f 100644 --- a/optimizely/project_config.py +++ b/optimizely/project_config.py @@ -88,6 +88,38 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): region_value = config.get('region') self.region: str = region_value or 'US' + self.holdouts: list[dict[str, Any]] = config.get('holdouts', []) + self.holdout_id_map: dict[str, dict[str, Any]] = {} + self.global_holdouts: dict[str, dict[str, Any]] = {} + self.included_holdouts: dict[str, list[dict[str, Any]]] = {} + self.excluded_holdouts: dict[str, list[dict[str, Any]]] = {} + self.flag_holdouts_map: dict[str, list[dict[str, Any]]] = {} + + for holdout in self.holdouts: + if holdout.get('status') != 'Running': + continue + + holdout_id = holdout['id'] + self.holdout_id_map[holdout_id] = holdout + + included_flags = holdout.get('includedFlags') + if not included_flags: + # This is a global holdout + self.global_holdouts[holdout_id] = holdout + + excluded_flags = holdout.get('excludedFlags') + if excluded_flags: + for flag_id in excluded_flags: + if flag_id not in self.excluded_holdouts: + self.excluded_holdouts[flag_id] = [] + self.excluded_holdouts[flag_id].append(holdout) + else: + # This holdout applies to specific flags + for flag_id in included_flags: + if flag_id not in self.included_holdouts: + self.included_holdouts[flag_id] = [] + self.included_holdouts[flag_id].append(holdout) + # Utility maps for quick lookup self.group_id_map: dict[str, entities.Group] = self._generate_key_map(self.groups, 'id', entities.Group) self.experiment_id_map: dict[str, entities.Experiment] = self._generate_key_map( @@ -752,3 +784,62 @@ def get_flag_variation( return variation return None + + def get_holdouts_for_flag(self, flag_key: str) -> list[Any]: + """ Helper method to get holdouts from an applied feature flag. + + Args: + flag_key: Key of the feature flag. + + Returns: + The holdouts that apply for a specific flag. + """ + feature_flag = self.feature_key_map.get(flag_key) + if not feature_flag: + return [] + + flag_id = feature_flag.id + + # Check cache first + if flag_id in self.flag_holdouts_map: + return self.flag_holdouts_map[flag_id] + + holdouts = [] + + # Add global holdouts that don't exclude this flag + for holdout in self.global_holdouts.values(): + is_excluded = False + excluded_flags = holdout.get('excludedFlags') + if excluded_flags: + for excluded_flag_id in excluded_flags: + if excluded_flag_id == flag_id: + is_excluded = True + break + if not is_excluded: + holdouts.append(holdout) + + # Add holdouts that specifically include this flag + if flag_id in self.included_holdouts: + holdouts.extend(self.included_holdouts[flag_id]) + + # Cache the result + self.flag_holdouts_map[flag_id] = holdouts + + return holdouts + + def get_holdout(self, holdout_id: str) -> Optional[dict[str, Any]]: + """ Helper method to get holdout from holdout ID. + + Args: + holdout_id: ID of the holdout. + + Returns: + The holdout corresponding to the provided holdout ID. + """ + holdout = self.holdout_id_map.get(holdout_id) + + if holdout: + return holdout + + self.logger.error(f'Holdout with ID "{holdout_id}" not found.') + return None diff --git a/requirements/core.txt b/requirements/core.txt index 7cbfe29f1..ea81c17b0 100644 --- a/requirements/core.txt +++ b/requirements/core.txt @@ -2,3 +2,4 @@ jsonschema>=3.2.0 pyrsistent>=0.16.0 requests>=2.21 idna>=2.10 +rpds-py<0.20.0; python_version < '3.11' diff --git a/requirements/typing.txt b/requirements/typing.txt index ba65f536a..4c01897b6 100644 --- a/requirements/typing.txt +++ b/requirements/typing.txt @@ -1,4 +1,5 @@ mypy types-jsonschema types-requests -types-Flask \ No newline at end of file +types-Flask +rpds-py<0.20.0; python_version < '3.11' \ No newline at end of file diff --git a/tests/test_config.py b/tests/test_config.py index a6e828c2e..08a81f6d8 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1375,3 +1375,162 @@ def test_get_variation_from_key_by_experiment_id_missing(self): variation = project_config.get_variation_from_key_by_experiment_id(experiment_id, variation_key) self.assertIsNone(variation) + + +class HoldoutConfigTest(base.BaseTest): + def setUp(self): + base.BaseTest.setUp(self) + + # Create config with holdouts + config_body_with_holdouts = self.config_dict_with_features.copy() + + # Use correct feature flag IDs from the datafile + boolean_feature_id = '91111' # boolean_single_variable_feature + multi_variate_feature_id = '91114' # test_feature_in_experiment_and_rollout + + config_body_with_holdouts['holdouts'] = [ + { + 'id': 'holdout_1', + 'key': 'global_holdout', + 'status': 'Running', + 'includedFlags': [], + 'excludedFlags': [boolean_feature_id] + }, + { + 'id': 'holdout_2', + 'key': 'specific_holdout', + 'status': 'Running', + 'includedFlags': [multi_variate_feature_id], + 'excludedFlags': [] + }, + { + 'id': 'holdout_3', + 'key': 'inactive_holdout', + 'status': 'Inactive', + 'includedFlags': [boolean_feature_id], + 'excludedFlags': [] + } + ] + + self.config_json_with_holdouts = json.dumps(config_body_with_holdouts) + opt_obj = optimizely.Optimizely(self.config_json_with_holdouts) + self.config_with_holdouts = opt_obj.config_manager.get_config() + + def test_get_holdouts_for_flag__non_existent_flag(self): + """ Test that get_holdouts_for_flag returns empty array for non-existent flag. """ + + holdouts = self.config_with_holdouts.get_holdouts_for_flag('non_existent_flag') + self.assertEqual([], holdouts) + + def test_get_holdouts_for_flag__returns_global_and_specific_holdouts(self): + """ Test that get_holdouts_for_flag returns global holdouts that do not exclude the flag + and specific holdouts that include the flag. """ + + holdouts = self.config_with_holdouts.get_holdouts_for_flag('test_feature_in_experiment_and_rollout') + self.assertEqual(2, len(holdouts)) + + global_holdout = next((h for h in holdouts if h['key'] == 'global_holdout'), None) + self.assertIsNotNone(global_holdout) + self.assertEqual('holdout_1', global_holdout['id']) + + specific_holdout = next((h for h in holdouts if h['key'] == 'specific_holdout'), None) + self.assertIsNotNone(specific_holdout) + self.assertEqual('holdout_2', specific_holdout['id']) + + def test_get_holdouts_for_flag__excludes_global_holdouts_for_excluded_flags(self): + """ Test that get_holdouts_for_flag does not return global holdouts that exclude the flag. """ + + holdouts = self.config_with_holdouts.get_holdouts_for_flag('boolean_single_variable_feature') + self.assertEqual(0, len(holdouts)) + + global_holdout = next((h for h in holdouts if h['key'] == 'global_holdout'), None) + self.assertIsNone(global_holdout) + + def test_get_holdouts_for_flag__caches_results(self): + """ Test that get_holdouts_for_flag caches results for subsequent calls. """ + + holdouts1 = self.config_with_holdouts.get_holdouts_for_flag('test_feature_in_experiment_and_rollout') + holdouts2 = self.config_with_holdouts.get_holdouts_for_flag('test_feature_in_experiment_and_rollout') + + # Should be the same object (cached) + self.assertIs(holdouts1, holdouts2) + self.assertEqual(2, len(holdouts1)) + + def test_get_holdouts_for_flag__returns_only_global_for_non_targeted_flags(self): + """ Test that get_holdouts_for_flag returns only global holdouts for flags not specifically targeted. """ + + holdouts = self.config_with_holdouts.get_holdouts_for_flag('test_feature_in_rollout') + + # Should only include global holdout (not excluded and no specific targeting) + self.assertEqual(1, len(holdouts)) + self.assertEqual('global_holdout', holdouts[0]['key']) + + def test_get_holdout__returns_holdout_for_valid_id(self): + """ Test that get_holdout returns holdout when valid ID is provided. """ + + holdout = self.config_with_holdouts.get_holdout('holdout_1') + self.assertIsNotNone(holdout) + self.assertEqual('holdout_1', holdout['id']) + self.assertEqual('global_holdout', holdout['key']) + self.assertEqual('Running', holdout['status']) + + def test_get_holdout__returns_holdout_regardless_of_status(self): + """ Test that get_holdout returns holdout regardless of status when valid ID is provided. """ + + holdout = self.config_with_holdouts.get_holdout('holdout_2') + self.assertIsNotNone(holdout) + self.assertEqual('holdout_2', holdout['id']) + self.assertEqual('specific_holdout', holdout['key']) + self.assertEqual('Running', holdout['status']) + + def test_get_holdout__returns_none_for_non_existent_id(self): + """ Test that get_holdout returns None for non-existent holdout ID. """ + + holdout = self.config_with_holdouts.get_holdout('non_existent_holdout') + self.assertIsNone(holdout) + + def test_get_holdout__logs_error_when_not_found(self): + """ Test that get_holdout logs error when holdout is not found. """ + + with mock.patch.object(self.config_with_holdouts, 'logger') as mock_logger: + result = self.config_with_holdouts.get_holdout('invalid_holdout_id') + + self.assertIsNone(result) + mock_logger.error.assert_called_once_with('Holdout with ID "invalid_holdout_id" not found.') + + def test_get_holdout__does_not_log_when_found(self): + """ Test that get_holdout does not log when holdout is found. """ + + with mock.patch.object(self.config_with_holdouts, 'logger') as mock_logger: + result = self.config_with_holdouts.get_holdout('holdout_1') + + self.assertIsNotNone(result) + mock_logger.error.assert_not_called() + + def test_holdout_initialization__categorizes_holdouts_properly(self): + """ Test that holdouts are properly categorized during initialization. """ + + self.assertIn('holdout_1', self.config_with_holdouts.holdout_id_map) + self.assertIn('holdout_2', self.config_with_holdouts.holdout_id_map) + self.assertIn('holdout_1', self.config_with_holdouts.global_holdouts) + + # Use correct feature flag IDs + boolean_feature_id = '91111' + multi_variate_feature_id = '91114' + + self.assertIn(multi_variate_feature_id, self.config_with_holdouts.included_holdouts) + self.assertTrue(len(self.config_with_holdouts.included_holdouts[multi_variate_feature_id]) > 0) + self.assertNotIn(boolean_feature_id, self.config_with_holdouts.included_holdouts) + + self.assertIn(boolean_feature_id, self.config_with_holdouts.excluded_holdouts) + self.assertTrue(len(self.config_with_holdouts.excluded_holdouts[boolean_feature_id]) > 0) + + def test_holdout_initialization__only_processes_running_holdouts(self): + """ Test that only running holdouts are processed during initialization. """ + + self.assertNotIn('holdout_3', self.config_with_holdouts.holdout_id_map) + self.assertNotIn('holdout_3', self.config_with_holdouts.global_holdouts) + + boolean_feature_id = '91111' + included_for_boolean = self.config_with_holdouts.included_holdouts.get(boolean_feature_id) + self.assertIsNone(included_for_boolean) From caba59741e577fd5b984a7bb3190bf52be3bf385 Mon Sep 17 00:00:00 2001 From: Farhan Anjum Date: Tue, 4 Nov 2025 06:21:35 +0600 Subject: [PATCH 03/32] [FSSDK-11991] update: expose CMAB cache configuration options (#463) * Enhance CMAB decision handling by returning reasons for decisions and updating type hints * Refactor CMAB cache settings and add convenience methods for cache size and TTL configuration * Refactor CMAB cache type hints for improved clarity and type safety * Fix return type hint for set_cmab_custom_cache method to improve type safety * Changed default cmab cache size to match odp --- optimizely/cmab/cmab_client.py | 2 +- optimizely/cmab/cmab_service.py | 51 +++++++++++++++++--- optimizely/decision_service.py | 3 +- optimizely/event/event_processor.py | 2 +- optimizely/optimizely.py | 31 +++++++------ optimizely/optimizely_factory.py | 72 ++++++++++++++++++++++++++++- tests/test_cmab_service.py | 10 ++-- tests/test_decision_service.py | 11 +++-- 8 files changed, 147 insertions(+), 35 deletions(-) diff --git a/optimizely/cmab/cmab_client.py b/optimizely/cmab/cmab_client.py index dfcffa781..25c185189 100644 --- a/optimizely/cmab/cmab_client.py +++ b/optimizely/cmab/cmab_client.py @@ -20,7 +20,7 @@ from optimizely.exceptions import CmabFetchError, CmabInvalidResponseError # Default constants for CMAB requests -DEFAULT_MAX_RETRIES = 3 +DEFAULT_MAX_RETRIES = 1 DEFAULT_INITIAL_BACKOFF = 0.1 # in seconds (100 ms) DEFAULT_MAX_BACKOFF = 10 # in seconds DEFAULT_BACKOFF_MULTIPLIER = 2.0 diff --git a/optimizely/cmab/cmab_service.py b/optimizely/cmab/cmab_service.py index 82c2c2061..00e996ca5 100644 --- a/optimizely/cmab/cmab_service.py +++ b/optimizely/cmab/cmab_service.py @@ -15,7 +15,7 @@ import hashlib import threading -from typing import Optional, List, TypedDict +from typing import Optional, List, TypedDict, Tuple from optimizely.cmab.cmab_client import DefaultCmabClient from optimizely.odp.lru_cache import LRUCache from optimizely.optimizely_user_context import OptimizelyUserContext, UserAttributes @@ -23,7 +23,10 @@ from optimizely.decision.optimizely_decide_option import OptimizelyDecideOption from optimizely import logger as _logging from optimizely.lib import pymmh3 as mmh3 + NUM_LOCK_STRIPES = 1000 +DEFAULT_CMAB_CACHE_TIMEOUT = 30 * 60 # 30 minutes +DEFAULT_CMAB_CACHE_SIZE = 10000 class CmabDecision(TypedDict): @@ -65,26 +68,40 @@ def _get_lock_index(self, user_id: str, rule_id: str) -> int: return hash_value % NUM_LOCK_STRIPES def get_decision(self, project_config: ProjectConfig, user_context: OptimizelyUserContext, - rule_id: str, options: List[str]) -> CmabDecision: + rule_id: str, options: List[str]) -> Tuple[CmabDecision, List[str]]: lock_index = self._get_lock_index(user_context.user_id, rule_id) with self.locks[lock_index]: return self._get_decision(project_config, user_context, rule_id, options) def _get_decision(self, project_config: ProjectConfig, user_context: OptimizelyUserContext, - rule_id: str, options: List[str]) -> CmabDecision: + rule_id: str, options: List[str]) -> Tuple[CmabDecision, List[str]]: filtered_attributes = self._filter_attributes(project_config, user_context, rule_id) + reasons = [] if OptimizelyDecideOption.IGNORE_CMAB_CACHE in options: - return self._fetch_decision(rule_id, user_context.user_id, filtered_attributes) + reason = f"Ignoring CMAB cache for user '{user_context.user_id}' and rule '{rule_id}'" + if self.logger: + self.logger.debug(reason) + reasons.append(reason) + cmab_decision = self._fetch_decision(rule_id, user_context.user_id, filtered_attributes) + return cmab_decision, reasons if OptimizelyDecideOption.RESET_CMAB_CACHE in options: + reason = f"Resetting CMAB cache for user '{user_context.user_id}' and rule '{rule_id}'" + if self.logger: + self.logger.debug(reason) + reasons.append(reason) self.cmab_cache.reset() cache_key = self._get_cache_key(user_context.user_id, rule_id) if OptimizelyDecideOption.INVALIDATE_USER_CMAB_CACHE in options: + reason = f"Invalidating CMAB cache for user '{user_context.user_id}' and rule '{rule_id}'" + if self.logger: + self.logger.debug(reason) + reasons.append(reason) self.cmab_cache.remove(cache_key) cached_value = self.cmab_cache.lookup(cache_key) @@ -93,17 +110,39 @@ def _get_decision(self, project_config: ProjectConfig, user_context: OptimizelyU if cached_value: if cached_value['attributes_hash'] == attributes_hash: - return CmabDecision(variation_id=cached_value['variation_id'], cmab_uuid=cached_value['cmab_uuid']) + reason = f"CMAB cache hit for user '{user_context.user_id}' and rule '{rule_id}'" + if self.logger: + self.logger.debug(reason) + reasons.append(reason) + return CmabDecision(variation_id=cached_value['variation_id'], + cmab_uuid=cached_value['cmab_uuid']), reasons else: + reason = ( + f"CMAB cache attributes mismatch for user '{user_context.user_id}' " + f"and rule '{rule_id}', fetching new decision." + ) + if self.logger: + self.logger.debug(reason) + reasons.append(reason) self.cmab_cache.remove(cache_key) + else: + reason = f"CMAB cache miss for user '{user_context.user_id}' and rule '{rule_id}'" + if self.logger: + self.logger.debug(reason) + reasons.append(reason) cmab_decision = self._fetch_decision(rule_id, user_context.user_id, filtered_attributes) + reason = f"CMAB decision is {cmab_decision}" + if self.logger: + self.logger.debug(reason) + reasons.append(reason) + self.cmab_cache.save(cache_key, { 'attributes_hash': attributes_hash, 'variation_id': cmab_decision['variation_id'], 'cmab_uuid': cmab_decision['cmab_uuid'], }) - return cmab_decision + return cmab_decision, reasons def _fetch_decision(self, rule_id: str, user_id: str, attributes: UserAttributes) -> CmabDecision: cmab_uuid = str(uuid.uuid4()) diff --git a/optimizely/decision_service.py b/optimizely/decision_service.py index d22bec87c..f843730e9 100644 --- a/optimizely/decision_service.py +++ b/optimizely/decision_service.py @@ -175,9 +175,10 @@ def _get_decision_for_cmab_experiment( # User is in CMAB allocation, proceed to CMAB decision try: options_list = list(options) if options is not None else [] - cmab_decision = self.cmab_service.get_decision( + cmab_decision, cmab_reasons = self.cmab_service.get_decision( project_config, user_context, experiment.id, options_list ) + decide_reasons.extend(cmab_reasons) return { "error": False, "result": cmab_decision, diff --git a/optimizely/event/event_processor.py b/optimizely/event/event_processor.py index 4fba29ebd..bdce6d9da 100644 --- a/optimizely/event/event_processor.py +++ b/optimizely/event/event_processor.py @@ -72,7 +72,7 @@ class Signal: def __init__( self, - event_dispatcher: Optional[type[EventDispatcher] | CustomEventDispatcher] = None, + event_dispatcher: Optional[EventDispatcher | CustomEventDispatcher] = None, logger: Optional[_logging.Logger] = None, start_on_init: bool = False, event_queue: Optional[queue.Queue[UserEvent | Signal]] = None, diff --git a/optimizely/optimizely.py b/optimizely/optimizely.py index ae433cb17..4a47bbdba 100644 --- a/optimizely/optimizely.py +++ b/optimizely/optimizely.py @@ -46,17 +46,13 @@ from .optimizely_user_context import OptimizelyUserContext, UserAttributes from .project_config import ProjectConfig from .cmab.cmab_client import DefaultCmabClient, CmabRetryConfig -from .cmab.cmab_service import DefaultCmabService, CmabCacheValue +from .cmab.cmab_service import DefaultCmabService, CmabCacheValue, DEFAULT_CMAB_CACHE_SIZE, DEFAULT_CMAB_CACHE_TIMEOUT if TYPE_CHECKING: # prevent circular dependency by skipping import at runtime from .user_profile import UserProfileService from .helpers.event_tag_utils import EventTags -# Default constants for CMAB cache -DEFAULT_CMAB_CACHE_TIMEOUT = 30 * 60 * 1000 # 30 minutes in milliseconds -DEFAULT_CMAB_CACHE_SIZE = 1000 - class Optimizely: """ Class encapsulating all SDK functionality. """ @@ -77,6 +73,7 @@ def __init__( default_decide_options: Optional[list[str]] = None, event_processor_options: Optional[dict[str, Any]] = None, settings: Optional[OptimizelySdkSettings] = None, + cmab_service: Optional[DefaultCmabService] = None, ) -> None: """ Optimizely init method for managing Custom projects. @@ -178,16 +175,20 @@ def __init__( self.event_builder = event_builder.EventBuilder() # Initialize CMAB components - self.cmab_client = DefaultCmabClient( - retry_config=CmabRetryConfig(), - logger=self.logger - ) - self.cmab_cache: LRUCache[str, CmabCacheValue] = LRUCache(DEFAULT_CMAB_CACHE_SIZE, DEFAULT_CMAB_CACHE_TIMEOUT) - self.cmab_service = DefaultCmabService( - cmab_cache=self.cmab_cache, - cmab_client=self.cmab_client, - logger=self.logger - ) + if cmab_service: + self.cmab_service = cmab_service + else: + self.cmab_client = DefaultCmabClient( + retry_config=CmabRetryConfig(), + logger=self.logger + ) + self.cmab_cache: LRUCache[str, CmabCacheValue] = LRUCache(DEFAULT_CMAB_CACHE_SIZE, + DEFAULT_CMAB_CACHE_TIMEOUT) + self.cmab_service = DefaultCmabService( + cmab_cache=self.cmab_cache, + cmab_client=self.cmab_client, + logger=self.logger + ) self.decision_service = decision_service.DecisionService(self.logger, user_profile_service, self.cmab_service) self.user_profile_service = user_profile_service diff --git a/optimizely/optimizely_factory.py b/optimizely/optimizely_factory.py index ae4669796..85dccd4f7 100644 --- a/optimizely/optimizely_factory.py +++ b/optimizely/optimizely_factory.py @@ -22,6 +22,9 @@ from .event_dispatcher import EventDispatcher, CustomEventDispatcher from .notification_center import NotificationCenter from .optimizely import Optimizely +from .odp.lru_cache import LRUCache +from .cmab.cmab_client import DefaultCmabClient, CmabRetryConfig +from .cmab.cmab_service import DefaultCmabService, CmabCacheValue, DEFAULT_CMAB_CACHE_TIMEOUT, DEFAULT_CMAB_CACHE_SIZE if TYPE_CHECKING: # prevent circular dependenacy by skipping import at runtime @@ -36,6 +39,9 @@ class OptimizelyFactory: max_event_flush_interval: Optional[int] = None polling_interval: Optional[float] = None blocking_timeout: Optional[int] = None + cmab_cache_size: Optional[int] = None + cmab_cache_ttl: Optional[int] = None + cmab_custom_cache: Optional[LRUCache[str, CmabCacheValue]] = None @staticmethod def set_batch_size(batch_size: int) -> int: @@ -75,6 +81,51 @@ def set_blocking_timeout(blocking_timeout: int) -> int: OptimizelyFactory.blocking_timeout = blocking_timeout return OptimizelyFactory.blocking_timeout + @staticmethod + def set_cmab_cache_size(cache_size: int, logger: Optional[optimizely_logger.Logger] = None) -> Optional[int]: + """ Convenience method for setting the maximum number of items in CMAB cache. + Args: + cache_size: Maximum number of items in CMAB cache. + logger: Optional logger for logging messages. + """ + logger = logger or optimizely_logger.NoOpLogger() + + if not isinstance(cache_size, int) or cache_size <= 0: + logger.error( + f"CMAB cache size is invalid, setting to default size {DEFAULT_CMAB_CACHE_SIZE}." + ) + return None + + OptimizelyFactory.cmab_cache_size = cache_size + return OptimizelyFactory.cmab_cache_size + + @staticmethod + def set_cmab_cache_ttl(cache_ttl: int, logger: Optional[optimizely_logger.Logger] = None) -> Optional[int]: + """ Convenience method for setting CMAB cache TTL. + Args: + cache_ttl: Time in seconds for cache entries to live. + logger: Optional logger for logging messages. + """ + logger = logger or optimizely_logger.NoOpLogger() + + if not isinstance(cache_ttl, (int, float)) or cache_ttl <= 0: + logger.error( + f"CMAB cache TTL is invalid, setting to default TTL {DEFAULT_CMAB_CACHE_TIMEOUT}." + ) + return None + + OptimizelyFactory.cmab_cache_ttl = int(cache_ttl) + return OptimizelyFactory.cmab_cache_ttl + + @staticmethod + def set_cmab_custom_cache(custom_cache: LRUCache[str, CmabCacheValue]) -> LRUCache[str, CmabCacheValue]: + """ Convenience method for setting custom CMAB cache. + Args: + custom_cache: Cache implementation with lookup, save, remove, and reset methods. + """ + OptimizelyFactory.cmab_custom_cache = custom_cache + return OptimizelyFactory.cmab_custom_cache + @staticmethod def default_instance(sdk_key: str, datafile: Optional[str] = None) -> Optimizely: """ Returns a new optimizely instance.. @@ -104,9 +155,17 @@ def default_instance(sdk_key: str, datafile: Optional[str] = None) -> Optimizely notification_center=notification_center, ) + # Initialize CMAB components + cmab_client = DefaultCmabClient(retry_config=CmabRetryConfig(), logger=logger) + cmab_cache = OptimizelyFactory.cmab_custom_cache or LRUCache( + OptimizelyFactory.cmab_cache_size or DEFAULT_CMAB_CACHE_SIZE, + OptimizelyFactory.cmab_cache_ttl or DEFAULT_CMAB_CACHE_TIMEOUT + ) + cmab_service = DefaultCmabService(cmab_cache, cmab_client, logger) + optimizely = Optimizely( datafile, None, logger, error_handler, None, None, sdk_key, config_manager, notification_center, - event_processor + event_processor, cmab_service=cmab_service ) return optimizely @@ -174,7 +233,16 @@ def custom_instance( notification_center=notification_center, ) + # Initialize CMAB components + cmab_client = DefaultCmabClient(retry_config=CmabRetryConfig(), logger=logger) + cmab_cache = OptimizelyFactory.cmab_custom_cache or LRUCache( + OptimizelyFactory.cmab_cache_size or DEFAULT_CMAB_CACHE_SIZE, + OptimizelyFactory.cmab_cache_ttl or DEFAULT_CMAB_CACHE_TIMEOUT + ) + cmab_service = DefaultCmabService(cmab_cache, cmab_client, logger) + return Optimizely( datafile, event_dispatcher, logger, error_handler, skip_json_validation, user_profile_service, - sdk_key, config_manager, notification_center, event_processor, settings=settings + sdk_key, config_manager, notification_center, event_processor, settings=settings, + cmab_service=cmab_service ) diff --git a/tests/test_cmab_service.py b/tests/test_cmab_service.py index 5aede6954..b26e277f7 100644 --- a/tests/test_cmab_service.py +++ b/tests/test_cmab_service.py @@ -60,7 +60,7 @@ def test_returns_decision_from_cache_when_valid(self): "cmab_uuid": "uuid-123" } - decision = self.cmab_service.get_decision( + decision, _ = self.cmab_service.get_decision( self.mock_project_config, self.mock_user_context, "exp1", [] ) @@ -72,7 +72,7 @@ def test_ignores_cache_when_option_given(self): self.mock_cmab_client.fetch_decision.return_value = "varB" expected_attributes = {"age": 25, "location": "USA"} - decision = self.cmab_service.get_decision( + decision, _ = self.cmab_service.get_decision( self.mock_project_config, self.mock_user_context, "exp1", @@ -105,7 +105,7 @@ def test_invalidates_user_cache_when_option_given(self): def test_resets_cache_when_option_given(self): self.mock_cmab_client.fetch_decision.return_value = "varD" - decision = self.cmab_service.get_decision( + decision, _ = self.cmab_service.get_decision( self.mock_project_config, self.mock_user_context, "exp1", @@ -128,7 +128,7 @@ def test_new_decision_when_hash_changes(self): expected_hash = self.cmab_service._hash_attributes(expected_attribute) expected_key = self.cmab_service._get_cache_key("user123", "exp1") - decision = self.cmab_service.get_decision(self.mock_project_config, self.mock_user_context, "exp1", []) + decision, _ = self.cmab_service.get_decision(self.mock_project_config, self.mock_user_context, "exp1", []) self.mock_cmab_cache.remove.assert_called_once_with(expected_key) self.mock_cmab_cache.save.assert_called_once_with( expected_key, @@ -171,7 +171,7 @@ def test_only_cmab_attributes_passed_to_client(self): } self.mock_cmab_client.fetch_decision.return_value = "varF" - decision = self.cmab_service.get_decision( + decision, _ = self.cmab_service.get_decision( self.mock_project_config, self.mock_user_context, "exp1", diff --git a/tests/test_decision_service.py b/tests/test_decision_service.py index d906a3cfc..dbcb74365 100644 --- a/tests/test_decision_service.py +++ b/tests/test_decision_service.py @@ -792,10 +792,13 @@ def test_get_variation_cmab_experiment_user_in_traffic_allocation(self): 'logger') as mock_logger: # Configure CMAB service to return a decision - mock_cmab_service.get_decision.return_value = { - 'variation_id': '111151', - 'cmab_uuid': 'test-cmab-uuid-123' - } + mock_cmab_service.get_decision.return_value = ( + { + 'variation_id': '111151', + 'cmab_uuid': 'test-cmab-uuid-123' + }, + [] # reasons list + ) # Call get_variation with the CMAB experiment variation_result = self.decision_service.get_variation( From 194fa145b0496d58ec4fc62d88f6ce5428bc45a1 Mon Sep 17 00:00:00 2001 From: Matjaz Pirnovar Date: Wed, 5 Nov 2025 20:23:23 -0800 Subject: [PATCH 04/32] [FSSDK-12010] Expose cmab prediction endpoint in py sdk (#466) * expose cmab prediction endpoint * fix typing requirement - exclude py version 3.11 and up * Add rpds-py restriction to core requirements for Python < 3.11 --- optimizely/cmab/cmab_client.py | 9 +++- optimizely/helpers/sdk_settings.py | 6 ++- optimizely/optimizely.py | 8 ++- tests/test_cmab_client.py | 78 ++++++++++++++++++++++++++++++ tests/test_config_manager.py | 6 ++- 5 files changed, 101 insertions(+), 6 deletions(-) diff --git a/optimizely/cmab/cmab_client.py b/optimizely/cmab/cmab_client.py index 25c185189..4880b0bbb 100644 --- a/optimizely/cmab/cmab_client.py +++ b/optimizely/cmab/cmab_client.py @@ -25,6 +25,7 @@ DEFAULT_MAX_BACKOFF = 10 # in seconds DEFAULT_BACKOFF_MULTIPLIER = 2.0 MAX_WAIT_TIME = 10.0 +DEFAULT_PREDICTION_ENDPOINT = "https://prediction.cmab.optimizely.com/predict/{}" class CmabRetryConfig: @@ -52,17 +53,21 @@ class DefaultCmabClient: """ def __init__(self, http_client: Optional[requests.Session] = None, retry_config: Optional[CmabRetryConfig] = None, - logger: Optional[_logging.Logger] = None): + logger: Optional[_logging.Logger] = None, + prediction_endpoint: Optional[str] = None): """Initialize the CMAB client. Args: http_client (Optional[requests.Session]): HTTP client for making requests. retry_config (Optional[CmabRetryConfig]): Configuration for retry logic. logger (Optional[_logging.Logger]): Logger for logging messages. + prediction_endpoint (Optional[str]): Custom prediction endpoint URL template. + Use {} as placeholder for rule_id. """ self.http_client = http_client or requests.Session() self.retry_config = retry_config self.logger = _logging.adapt_logger(logger or _logging.NoOpLogger()) + self.prediction_endpoint = prediction_endpoint or DEFAULT_PREDICTION_ENDPOINT def fetch_decision( self, @@ -84,7 +89,7 @@ def fetch_decision( Returns: str: The variation ID. """ - url = f"https://prediction.cmab.optimizely.com/predict/{rule_id}" + url = self.prediction_endpoint.format(rule_id) cmab_attributes = [ {"id": key, "value": value, "type": "custom_attribute"} for key, value in attributes.items() diff --git a/optimizely/helpers/sdk_settings.py b/optimizely/helpers/sdk_settings.py index 6b31ee9c9..e5e7aeb1f 100644 --- a/optimizely/helpers/sdk_settings.py +++ b/optimizely/helpers/sdk_settings.py @@ -33,7 +33,8 @@ def __init__( odp_event_manager: Optional[OdpEventManager] = None, odp_segment_request_timeout: Optional[int] = None, odp_event_request_timeout: Optional[int] = None, - odp_event_flush_interval: Optional[int] = None + odp_event_flush_interval: Optional[int] = None, + cmab_prediction_endpoint: Optional[str] = None ) -> None: """ Args: @@ -52,6 +53,8 @@ def __init__( send successfully (optional). odp_event_request_timeout: Time to wait in seconds for send_odp_events request to send successfully. odp_event_flush_interval: Time to wait for events to accumulate before sending a batch in seconds (optional). + cmab_prediction_endpoint: Custom CMAB prediction endpoint URL template (optional). + Use {} as placeholder for rule_id. Defaults to production endpoint if not provided. """ self.odp_disabled = odp_disabled @@ -63,3 +66,4 @@ def __init__( self.fetch_segments_timeout = odp_segment_request_timeout self.odp_event_timeout = odp_event_request_timeout self.odp_flush_interval = odp_event_flush_interval + self.cmab_prediction_endpoint = cmab_prediction_endpoint diff --git a/optimizely/optimizely.py b/optimizely/optimizely.py index 4a47bbdba..6a1acaf2c 100644 --- a/optimizely/optimizely.py +++ b/optimizely/optimizely.py @@ -178,9 +178,15 @@ def __init__( if cmab_service: self.cmab_service = cmab_service else: + # Get custom prediction endpoint from settings if provided + cmab_prediction_endpoint = None + if self.sdk_settings and self.sdk_settings.cmab_prediction_endpoint: + cmab_prediction_endpoint = self.sdk_settings.cmab_prediction_endpoint + self.cmab_client = DefaultCmabClient( retry_config=CmabRetryConfig(), - logger=self.logger + logger=self.logger, + prediction_endpoint=cmab_prediction_endpoint ) self.cmab_cache: LRUCache[str, CmabCacheValue] = LRUCache(DEFAULT_CMAB_CACHE_SIZE, DEFAULT_CMAB_CACHE_TIMEOUT) diff --git a/tests/test_cmab_client.py b/tests/test_cmab_client.py index 3aac5fd98..3613da761 100644 --- a/tests/test_cmab_client.py +++ b/tests/test_cmab_client.py @@ -245,3 +245,81 @@ def test_fetch_decision_exhausts_all_retry_attempts(self, mock_sleep): self.mock_logger.error.assert_called_with( Errors.CMAB_FETCH_FAILED.format('Exhausted all retries for CMAB request.') ) + + def test_custom_prediction_endpoint(self): + """Test that custom prediction endpoint is used correctly.""" + custom_endpoint = "https://custom.endpoint.com/predict/{}" + client = DefaultCmabClient( + http_client=self.mock_http_client, + logger=self.mock_logger, + prediction_endpoint=custom_endpoint + ) + + mock_response = MagicMock() + mock_response.status_code = 200 + mock_response.json.return_value = { + 'predictions': [{'variation_id': 'abc123'}] + } + self.mock_http_client.post.return_value = mock_response + + result = client.fetch_decision(self.rule_id, self.user_id, self.attributes, self.cmab_uuid) + + self.assertEqual(result, 'abc123') + expected_custom_url = custom_endpoint.format(self.rule_id) + self.mock_http_client.post.assert_called_once_with( + expected_custom_url, + data=json.dumps(self.expected_body), + headers=self.expected_headers, + timeout=10.0 + ) + + def test_default_prediction_endpoint(self): + """Test that default prediction endpoint is used when none is provided.""" + client = DefaultCmabClient( + http_client=self.mock_http_client, + logger=self.mock_logger + ) + + mock_response = MagicMock() + mock_response.status_code = 200 + mock_response.json.return_value = { + 'predictions': [{'variation_id': 'def456'}] + } + self.mock_http_client.post.return_value = mock_response + + result = client.fetch_decision(self.rule_id, self.user_id, self.attributes, self.cmab_uuid) + + self.assertEqual(result, 'def456') + # Should use the default production endpoint + self.mock_http_client.post.assert_called_once_with( + self.expected_url, + data=json.dumps(self.expected_body), + headers=self.expected_headers, + timeout=10.0 + ) + + def test_empty_prediction_endpoint_uses_default(self): + """Test that empty string prediction endpoint falls back to default.""" + client = DefaultCmabClient( + http_client=self.mock_http_client, + logger=self.mock_logger, + prediction_endpoint="" + ) + + mock_response = MagicMock() + mock_response.status_code = 200 + mock_response.json.return_value = { + 'predictions': [{'variation_id': 'ghi789'}] + } + self.mock_http_client.post.return_value = mock_response + + result = client.fetch_decision(self.rule_id, self.user_id, self.attributes, self.cmab_uuid) + + self.assertEqual(result, 'ghi789') + # Should use the default production endpoint when empty string is provided + self.mock_http_client.post.assert_called_once_with( + self.expected_url, + data=json.dumps(self.expected_body), + headers=self.expected_headers, + timeout=10.0 + ) diff --git a/tests/test_config_manager.py b/tests/test_config_manager.py index 56674381b..1930520e8 100644 --- a/tests/test_config_manager.py +++ b/tests/test_config_manager.py @@ -517,8 +517,10 @@ def test_fetch_datafile__exception_polling_thread_failed(self, _): log_messages = [args[0] for args, _ in mock_logger.error.call_args_list] for message in log_messages: print(message) - if "Thread for background datafile polling failed. " \ - "Error: timestamp too large to convert to C PyTime_t" not in message: + # Check for key parts of the error message (version-agnostic for Python 3.11+) + if not ("Thread for background datafile polling failed" in message and + "timestamp too large to convert to C" in message and + "PyTime_t" in message): assert False def test_is_running(self, _): From 368b5faa502b93044871bd85b75f7f5142252e6a Mon Sep 17 00:00:00 2001 From: esrakartalOpt <102107327+esrakartalOpt@users.noreply.github.com> Date: Wed, 12 Nov 2025 11:21:12 -0600 Subject: [PATCH 05/32] [FSSDK-11571] Python: Add holdout support and refactor decision logic in DefaultDecisionService (#467) * [FSSDK-11571] Python: Add holdout support and refactor decision logic in DefaultDecisionService * Fix all lint issues * Fix type issues * Fix type check error * Implement suggested comments * Implement suggested comments * Fix lint --- optimizely/bucketer.py | 82 +++- optimizely/decision_service.py | 184 +++++++- optimizely/helpers/enums.py | 1 + optimizely/helpers/types.py | 15 +- optimizely/optimizely.py | 93 +++- optimizely/project_config.py | 109 +++-- tests/test_bucketing_holdout.py | 360 ++++++++++++++++ tests/test_decision_service_holdout.py | 568 +++++++++++++++++++++++++ 8 files changed, 1325 insertions(+), 87 deletions(-) create mode 100644 tests/test_bucketing_holdout.py create mode 100644 tests/test_decision_service_holdout.py diff --git a/optimizely/bucketer.py b/optimizely/bucketer.py index a6e8323d6..ca4310126 100644 --- a/optimizely/bucketer.py +++ b/optimizely/bucketer.py @@ -119,16 +119,41 @@ def bucket( and array of log messages representing decision making. */. """ + # Check if experiment is None first + if not experiment: + message = 'Invalid entity key provided for bucketing. Returning nil.' + project_config.logger.debug(message) + return None, [] + + if isinstance(experiment, dict): + # This is a holdout dictionary + experiment_key = experiment.get('key', '') + experiment_id = experiment.get('id', '') + else: + # This is an Experiment object + experiment_key = experiment.key + experiment_id = experiment.id + + if not experiment_key or not experiment_key.strip(): + message = 'Invalid entity key provided for bucketing. Returning nil.' + project_config.logger.debug(message) + return None, [] + variation_id, decide_reasons = self.bucket_to_entity_id(project_config, experiment, user_id, bucketing_id) if variation_id: - variation = project_config.get_variation_from_id_by_experiment_id(experiment.id, variation_id) + if isinstance(experiment, dict): + # For holdouts, find the variation in the holdout's variations array + variations = experiment.get('variations', []) + variation = next((v for v in variations if v.get('id') == variation_id), None) + else: + # For experiments, use the existing method + variation = project_config.get_variation_from_id_by_experiment_id(experiment_id, variation_id) return variation, decide_reasons - else: - message = 'Bucketed into an empty traffic range. Returning nil.' - project_config.logger.info(message) - decide_reasons.append(message) - + # No variation found - log message for empty traffic range + message = 'Bucketed into an empty traffic range. Returning nil.' + project_config.logger.info(message) + decide_reasons.append(message) return None, decide_reasons def bucket_to_entity_id( @@ -151,9 +176,25 @@ def bucket_to_entity_id( if not experiment: return None, decide_reasons + # Handle both Experiment objects and holdout dictionaries + if isinstance(experiment, dict): + # This is a holdout dictionary - holdouts don't have groups + experiment_key = experiment.get('key', '') + experiment_id = experiment.get('id', '') + traffic_allocations = experiment.get('trafficAllocation', []) + has_cmab = False + group_policy = None + else: + # This is an Experiment object + experiment_key = experiment.key + experiment_id = experiment.id + traffic_allocations = experiment.trafficAllocation + has_cmab = bool(experiment.cmab) + group_policy = getattr(experiment, 'groupPolicy', None) + # Determine if experiment is in a mutually exclusive group. - # This will not affect evaluation of rollout rules. - if experiment.groupPolicy in GROUP_POLICIES: + # This will not affect evaluation of rollout rules or holdouts. + if group_policy and group_policy in GROUP_POLICIES: group = project_config.get_group(experiment.groupId) if not group: @@ -169,26 +210,27 @@ def bucket_to_entity_id( decide_reasons.append(message) return None, decide_reasons - if user_experiment_id != experiment.id: - message = f'User "{user_id}" is not in experiment "{experiment.key}" of group {experiment.groupId}.' + if user_experiment_id != experiment_id: + message = f'User "{user_id}" is not in experiment "{experiment_key}" of group {experiment.groupId}.' project_config.logger.info(message) decide_reasons.append(message) return None, decide_reasons - message = f'User "{user_id}" is in experiment {experiment.key} of group {experiment.groupId}.' + message = f'User "{user_id}" is in experiment {experiment_key} of group {experiment.groupId}.' project_config.logger.info(message) decide_reasons.append(message) - traffic_allocations: list[TrafficAllocation] = experiment.trafficAllocation - if experiment.cmab: - traffic_allocations = [ - { - "entityId": "$", - "endOfRange": experiment.cmab['trafficAllocation'] - } - ] + if has_cmab: + if experiment.cmab: + traffic_allocations = [ + { + "entityId": "$", + "endOfRange": experiment.cmab['trafficAllocation'] + } + ] + # Bucket user if not in white-list and in group (if any) variation_id = self.find_bucket(project_config, bucketing_id, - experiment.id, traffic_allocations) + experiment_id, traffic_allocations) return variation_id, decide_reasons diff --git a/optimizely/decision_service.py b/optimizely/decision_service.py index f843730e9..78be89d8e 100644 --- a/optimizely/decision_service.py +++ b/optimizely/decision_service.py @@ -12,7 +12,9 @@ # limitations under the License. from __future__ import annotations -from typing import TYPE_CHECKING, NamedTuple, Optional, Sequence, List, TypedDict +from typing import TYPE_CHECKING, NamedTuple, Optional, Sequence, List, TypedDict, Union + +from optimizely.helpers.types import HoldoutDict, VariationDict from . import bucketer from . import entities @@ -59,7 +61,7 @@ class VariationResult(TypedDict): cmab_uuid: Optional[str] error: bool reasons: List[str] - variation: Optional[entities.Variation] + variation: Optional[Union[entities.Variation, VariationDict]] class DecisionResult(TypedDict): @@ -80,7 +82,7 @@ class Decision(NamedTuple): """Named tuple containing selected experiment, variation, source and cmab_uuid. None if no experiment/variation was selected.""" experiment: Optional[entities.Experiment] - variation: Optional[entities.Variation] + variation: Optional[Union[entities.Variation, VariationDict]] source: Optional[str] cmab_uuid: Optional[str] @@ -670,7 +672,179 @@ def get_variation_for_feature( - 'error': Boolean indicating if an error occurred during the decision process. - 'reasons': List of log messages representing decision making for the feature. """ - return self.get_variations_for_feature_list(project_config, [feature], user_context, options)[0] + holdouts = project_config.get_holdouts_for_flag(feature.key) + + if holdouts: + # Has holdouts - use get_decision_for_flag which checks holdouts first + return self.get_decision_for_flag(feature, user_context, project_config, options) + else: + return self.get_variations_for_feature_list(project_config, [feature], user_context, options)[0] + + def get_decision_for_flag( + self, + feature_flag: entities.FeatureFlag, + user_context: OptimizelyUserContext, + project_config: ProjectConfig, + decide_options: Optional[Sequence[str]] = None, + user_profile_tracker: Optional[UserProfileTracker] = None, + decide_reasons: Optional[list[str]] = None + ) -> DecisionResult: + """ + Get the decision for a single feature flag. + Processes holdouts, experiments, and rollouts in that order. + + Args: + feature_flag: The feature flag to get a decision for. + user_context: The user context. + project_config: The project config. + decide_options: Sequence of decide options. + user_profile_tracker: The user profile tracker. + decide_reasons: List of decision reasons to merge. + + Returns: + A DecisionResult for the feature flag. + """ + reasons = decide_reasons.copy() if decide_reasons else [] + user_id = user_context.user_id + + # Check holdouts + holdouts = project_config.get_holdouts_for_flag(feature_flag.key) + for holdout in holdouts: + holdout_decision = self.get_variation_for_holdout(holdout, user_context, project_config) + reasons.extend(holdout_decision['reasons']) + + decision = holdout_decision['decision'] + # Check if user was bucketed into holdout (has a variation) + if decision.variation is None: + continue + + message = ( + f"The user '{user_id}' is bucketed into holdout '{holdout['key']}' " + f"for feature flag '{feature_flag.key}'." + ) + self.logger.info(message) + reasons.append(message) + return { + 'decision': holdout_decision['decision'], + 'error': False, + 'reasons': reasons + } + + # If no holdout decision, fall back to existing experiment/rollout logic + # Use get_variations_for_feature_list which handles experiments and rollouts + fallback_result = self.get_variations_for_feature_list( + project_config, [feature_flag], user_context, decide_options + )[0] + + # Merge reasons + if fallback_result.get('reasons'): + reasons.extend(fallback_result['reasons']) + + return { + 'decision': fallback_result['decision'], + 'error': fallback_result.get('error', False), + 'reasons': reasons + } + + def get_variation_for_holdout( + self, + holdout: HoldoutDict, + user_context: OptimizelyUserContext, + project_config: ProjectConfig + ) -> DecisionResult: + """ + Get the variation for holdout. + + Args: + holdout: The holdout configuration (HoldoutDict). + user_context: The user context. + project_config: The project config. + + Returns: + A DecisionResult for the holdout. + """ + from optimizely.helpers.enums import ExperimentAudienceEvaluationLogs + + decide_reasons: list[str] = [] + user_id = user_context.user_id + attributes = user_context.get_user_attributes() + + if not holdout or not holdout.get('status') or holdout.get('status') != 'Running': + key = holdout.get('key') if holdout else 'unknown' + message = f"Holdout '{key}' is not running." + self.logger.info(message) + decide_reasons.append(message) + return { + 'decision': Decision(None, None, enums.DecisionSources.HOLDOUT, None), + 'error': False, + 'reasons': decide_reasons + } + + bucketing_id, bucketing_id_reasons = self._get_bucketing_id(user_id, attributes) + decide_reasons.extend(bucketing_id_reasons) + + # Check audience conditions + audience_conditions = holdout.get('audienceIds') + user_meets_audience_conditions, reasons_received = audience_helper.does_user_meet_audience_conditions( + project_config, + audience_conditions, + ExperimentAudienceEvaluationLogs, + holdout.get('key', 'unknown'), + user_context, + self.logger + ) + decide_reasons.extend(reasons_received) + + if not user_meets_audience_conditions: + message = ( + f"User '{user_id}' does not meet the conditions for holdout " + f"'{holdout['key']}'." + ) + self.logger.debug(message) + decide_reasons.append(message) + return { + 'decision': Decision(None, None, enums.DecisionSources.HOLDOUT, None), + 'error': False, + 'reasons': decide_reasons + } + + # Bucket user into holdout variation + variation, bucket_reasons = self.bucketer.bucket( + project_config, holdout, user_id, bucketing_id # type: ignore[arg-type] + ) + decide_reasons.extend(bucket_reasons) + + if variation: + # For holdouts, variation is a dict, not a Variation entity + variation_key = variation['key'] if isinstance(variation, dict) else variation.key + message = ( + f"The user '{user_id}' is bucketed into variation '{variation_key}' " + f"of holdout '{holdout['key']}'." + ) + self.logger.info(message) + decide_reasons.append(message) + + # Create Decision for holdout - experiment is None, source is HOLDOUT + holdout_decision: Decision = Decision( + experiment=None, + variation=variation, + source=enums.DecisionSources.HOLDOUT, + cmab_uuid=None + ) + return { + 'decision': holdout_decision, + 'error': False, + 'reasons': decide_reasons + } + + message = f"User '{user_id}' is not bucketed into any variation for holdout '{holdout['key']}'." + self.logger.info(message) + decide_reasons.append(message) + return { + 'decision': Decision(None, None, enums.DecisionSources.HOLDOUT, None), + 'error': False, + 'reasons': decide_reasons + } def validated_forced_decision( self, @@ -779,7 +953,7 @@ def get_variations_for_feature_list( if feature.experimentIds: for experiment_id in feature.experimentIds: experiment = project_config.get_experiment_from_id(experiment_id) - decision_variation = None + decision_variation: Optional[Union[entities.Variation, VariationDict]] = None if experiment: optimizely_decision_context = OptimizelyUserContext.OptimizelyDecisionContext( diff --git a/optimizely/helpers/enums.py b/optimizely/helpers/enums.py index 4630491c4..74acdcfa6 100644 --- a/optimizely/helpers/enums.py +++ b/optimizely/helpers/enums.py @@ -99,6 +99,7 @@ class DecisionSources: EXPERIMENT: Final = 'experiment' FEATURE_TEST: Final = 'feature-test' ROLLOUT: Final = 'rollout' + HOLDOUT: Final = 'holdout' class Errors: diff --git a/optimizely/helpers/types.py b/optimizely/helpers/types.py index 3cca45de1..d4177dc0b 100644 --- a/optimizely/helpers/types.py +++ b/optimizely/helpers/types.py @@ -12,7 +12,7 @@ # limitations under the License. from __future__ import annotations -from typing import Optional, Any +from typing import Literal, Optional, Any from sys import version_info @@ -115,3 +115,16 @@ class CmabDict(BaseEntity): """Cmab dict from parsed datafile json.""" attributeIds: list[str] trafficAllocation: int + + +HoldoutStatus = Literal['Draft', 'Running', 'Concluded', 'Archived'] + + +class HoldoutDict(ExperimentDict): + """Holdout dict from parsed datafile json. + + Extends ExperimentDict with holdout-specific properties. + """ + holdoutStatus: HoldoutStatus + includedFlags: list[str] + excludedFlags: list[str] diff --git a/optimizely/optimizely.py b/optimizely/optimizely.py index 6a1acaf2c..b4c281ed1 100644 --- a/optimizely/optimizely.py +++ b/optimizely/optimizely.py @@ -13,7 +13,9 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any, Optional, Union + +from optimizely.helpers.types import VariationDict from . import decision_service @@ -198,6 +200,67 @@ def __init__( self.decision_service = decision_service.DecisionService(self.logger, user_profile_service, self.cmab_service) self.user_profile_service = user_profile_service + def _get_variation_key(self, variation: Optional[Union[entities.Variation, VariationDict]]) -> Optional[str]: + """Helper to extract variation key from either dict (holdout) or Variation object. + Args: + variation: Either a dict (from holdout) or entities.Variation object + Returns: + The variation key as a string, or None if not available + """ + if variation is None: + return None + + try: + # Try dict access first (for holdouts) + if isinstance(variation, dict): + return variation.get('key') + # Otherwise assume it's a Variation entity object + else: + return variation.key + except (AttributeError, KeyError, TypeError): + self.logger.warning(f"Unable to extract variation key from {type(variation)}") + return None + + def _get_variation_id(self, variation: Optional[Union[entities.Variation, VariationDict]]) -> Optional[str]: + """Helper to extract variation id from either dict (holdout) or Variation object. + Args: + variation: Either a dict (from holdout) or entities.Variation object + Returns: + The variation id as a string, or None if not available + """ + if variation is None: + return None + + try: + # Try dict access first (for holdouts) + if isinstance(variation, dict): + return variation.get('id') + # Otherwise assume it's a Variation entity object + else: + return variation.id + except (AttributeError, KeyError, TypeError): + self.logger.warning(f"Unable to extract variation id from {type(variation)}") + return None + + def _get_feature_enabled(self, variation: Optional[Union[entities.Variation, VariationDict]]) -> bool: + """Helper to extract featureEnabled flag from either dict (holdout) or Variation object. + Args: + variation: Either a dict (from holdout) or entities.Variation object + Returns: + The featureEnabled value, defaults to False if not available + """ + if variation is None: + return False + + try: + if isinstance(variation, dict): + feature_enabled = variation.get('featureEnabled', False) + return bool(feature_enabled) if feature_enabled is not None else False + else: + return variation.featureEnabled if hasattr(variation, 'featureEnabled') else False + except (AttributeError, KeyError, TypeError): + return False + def _validate_instantiation_options(self) -> None: """ Helper method to validate all instantiation parameters. @@ -267,7 +330,7 @@ def _validate_user_inputs( def _send_impression_event( self, project_config: project_config.ProjectConfig, experiment: Optional[entities.Experiment], - variation: Optional[entities.Variation], flag_key: str, rule_key: str, rule_type: str, + variation: Optional[Union[entities.Variation, VariationDict]], flag_key: str, rule_key: str, rule_type: str, enabled: bool, user_id: str, attributes: Optional[UserAttributes], cmab_uuid: Optional[str] = None ) -> None: """ Helper method to send impression event. @@ -286,7 +349,7 @@ def _send_impression_event( if not experiment: experiment = entities.Experiment.get_default() - variation_id = variation.id if variation is not None else None + variation_id = self._get_variation_id(variation) if variation is not None else None user_event = user_event_factory.UserEventFactory.create_impression_event( project_config, experiment, variation_id, flag_key, rule_key, rule_type, @@ -372,7 +435,7 @@ def _get_feature_variable_for_type( if decision.variation: - feature_enabled = decision.variation.featureEnabled + feature_enabled = self._get_feature_enabled(decision.variation) if feature_enabled: variable_value = project_config.get_variable_value_for_variation(variable, decision.variation) self.logger.info( @@ -393,7 +456,7 @@ def _get_feature_variable_for_type( if decision.source == enums.DecisionSources.FEATURE_TEST: source_info = { 'experiment_key': decision.experiment.key if decision.experiment else None, - 'variation_key': decision.variation.key if decision.variation else None, + 'variation_key': self._get_variation_key(decision.variation), } try: @@ -461,7 +524,7 @@ def _get_all_feature_variables_for_type( if decision.variation: - feature_enabled = decision.variation.featureEnabled + feature_enabled = self._get_feature_enabled(decision.variation) if feature_enabled: self.logger.info( f'Feature "{feature_key}" is enabled for user "{user_id}".' @@ -497,7 +560,7 @@ def _get_all_feature_variables_for_type( if decision.source == enums.DecisionSources.FEATURE_TEST: source_info = { 'experiment_key': decision.experiment.key if decision.experiment else None, - 'variation_key': decision.variation.key if decision.variation else None, + 'variation_key': self._get_variation_key(decision.variation), } self.notification_center.send_notifications( @@ -670,7 +733,7 @@ def get_variation( variation = variation_result['variation'] user_profile_tracker.save_user_profile() if variation: - variation_key = variation.key + variation_key = self._get_variation_key(variation) if project_config.is_feature_experiment(experiment.id): decision_notification_type = enums.DecisionNotificationTypes.FEATURE_TEST @@ -735,7 +798,7 @@ def is_feature_enabled(self, feature_key: str, user_id: str, attributes: Optiona is_source_rollout = decision.source == enums.DecisionSources.ROLLOUT if decision.variation: - if decision.variation.featureEnabled is True: + if self._get_feature_enabled(decision.variation) is True: feature_enabled = True if (is_source_rollout or not decision.variation) and project_config.get_send_flag_decisions_value(): @@ -748,7 +811,7 @@ def is_feature_enabled(self, feature_key: str, user_id: str, attributes: Optiona if is_source_experiment and decision.variation and decision.experiment: source_info = { 'experiment_key': decision.experiment.key, - 'variation_key': decision.variation.key, + 'variation_key': self._get_variation_key(decision.variation), } self._send_impression_event( project_config, decision.experiment, decision.variation, feature.key, decision.experiment.key, @@ -1182,7 +1245,7 @@ def _create_optimizely_decision( user_id = user_context.user_id feature_enabled = False if flag_decision.variation is not None: - if flag_decision.variation.featureEnabled: + if self._get_feature_enabled(flag_decision.variation): feature_enabled = True self.logger.info(f'Feature {flag_key} is enabled for user {user_id} {feature_enabled}"') @@ -1231,11 +1294,7 @@ def _create_optimizely_decision( all_variables[variable_key] = actual_value should_include_reasons = OptimizelyDecideOption.INCLUDE_REASONS in decide_options - variation_key = ( - flag_decision.variation.key - if flag_decision is not None and flag_decision.variation is not None - else None - ) + variation_key = self._get_variation_key(flag_decision.variation) experiment_id = None variation_id = None @@ -1248,7 +1307,7 @@ def _create_optimizely_decision( try: if flag_decision.variation is not None: - variation_id = flag_decision.variation.id + variation_id = self._get_variation_id(flag_decision.variation) except AttributeError: self.logger.warning("flag_decision.variation has no attribute 'id'") diff --git a/optimizely/project_config.py b/optimizely/project_config.py index 1e813462f..23508bb67 100644 --- a/optimizely/project_config.py +++ b/optimizely/project_config.py @@ -12,7 +12,7 @@ # limitations under the License. from __future__ import annotations import json -from typing import TYPE_CHECKING, Optional, Type, TypeVar, cast, Any, Iterable, List +from typing import TYPE_CHECKING, Optional, Type, TypeVar, Union, cast, Any, Iterable, List from sys import version_info from . import entities @@ -21,6 +21,8 @@ from .helpers import enums from .helpers import types +from optimizely.helpers.types import HoldoutDict, VariationDict + if version_info < (3, 8): from typing_extensions import Final else: @@ -88,12 +90,12 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): region_value = config.get('region') self.region: str = region_value or 'US' - self.holdouts: list[dict[str, Any]] = config.get('holdouts', []) - self.holdout_id_map: dict[str, dict[str, Any]] = {} - self.global_holdouts: dict[str, dict[str, Any]] = {} - self.included_holdouts: dict[str, list[dict[str, Any]]] = {} - self.excluded_holdouts: dict[str, list[dict[str, Any]]] = {} - self.flag_holdouts_map: dict[str, list[dict[str, Any]]] = {} + self.holdouts: list[HoldoutDict] = config.get('holdouts', []) + self.holdout_id_map: dict[str, HoldoutDict] = {} + self.global_holdouts: dict[str, HoldoutDict] = {} + self.included_holdouts: dict[str, list[HoldoutDict]] = {} + self.excluded_holdouts: dict[str, list[HoldoutDict]] = {} + self.flag_holdouts_map: dict[str, list[HoldoutDict]] = {} for holdout in self.holdouts: if holdout.get('status') != 'Running': @@ -218,6 +220,21 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): # Add this experiment in experiment-feature map. self.experiment_feature_map[exp_id] = [feature.id] rules.append(self.experiment_id_map[exp_id]) + + flag_id = feature.id + applicable_holdouts = [] + + if flag_id in self.included_holdouts: + applicable_holdouts.extend(self.included_holdouts[flag_id]) + + for holdout in self.global_holdouts.values(): + excluded_flag_ids = holdout.get('excludedFlags', []) + if flag_id not in excluded_flag_ids: + applicable_holdouts.append(holdout) + + if applicable_holdouts: + self.flag_holdouts_map[feature.key] = applicable_holdouts + rollout = None if len(feature.rolloutId) == 0 else self.rollout_id_map[feature.rolloutId] if rollout: for exp in rollout.experiments: @@ -231,6 +248,30 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): variations.append(rule_variation) self.flag_variations_map[feature.key] = variations + if self.holdouts: + for holdout in self.holdouts: + holdout_key = holdout.get('key') + holdout_id = holdout.get('id') + + if not holdout_key or not holdout_id: + continue + + self.variation_key_map[holdout_key] = {} + self.variation_id_map[holdout_key] = {} + self.variation_id_map_by_experiment_id[holdout_id] = {} + self.variation_key_map_by_experiment_id[holdout_id] = {} + + variations = holdout.get('variations') + if variations: + for variation in variations: + variation_key = variation.get('key') if isinstance(variation, dict) else None + variation_id = variation.get('id') if isinstance(variation, dict) else None + if variation_key and variation_id: + self.variation_key_map[holdout_key][variation_key] = variation + self.variation_id_map[holdout_key][variation_id] = variation + self.variation_key_map_by_experiment_id[holdout_id][variation_key] = variation + self.variation_id_map_by_experiment_id[holdout_id][variation_id] = variation + @staticmethod def _generate_key_map( entity_list: Iterable[Any], key: str, entity_class: Type[EntityClass], first_value: bool = False @@ -615,7 +656,7 @@ def get_rollout_from_id(self, rollout_id: str) -> Optional[entities.Layer]: return None def get_variable_value_for_variation( - self, variable: Optional[entities.Variable], variation: Optional[entities.Variation] + self, variable: Optional[entities.Variable], variation: Optional[Union[entities.Variation, VariationDict]] ) -> Optional[str]: """ Get the variable value for the given variation. @@ -629,12 +670,21 @@ def get_variable_value_for_variation( if not variable or not variation: return None - if variation.id not in self.variation_variable_usage_map: - self.logger.error(f'Variation with ID "{variation.id}" is not in the datafile.') + + # Extract variation ID from either Variation entity or dict + if isinstance(variation, dict): + variation_id = variation.get('id') + if not variation_id: + return None + else: + variation_id = variation.id + + if variation_id not in self.variation_variable_usage_map: + self.logger.error(f'Variation with ID "{variation_id}" is not in the datafile.') return None # Get all variable usages for the given variation - variable_usages = self.variation_variable_usage_map[variation.id] + variable_usages = self.variation_variable_usage_map[variation_id] # Find usage in given variation variable_usage = None @@ -643,7 +693,6 @@ def get_variable_value_for_variation( if variable_usage: variable_value = variable_usage.value - else: variable_value = variable.defaultValue @@ -785,7 +834,7 @@ def get_flag_variation( return None - def get_holdouts_for_flag(self, flag_key: str) -> list[Any]: + def get_holdouts_for_flag(self, flag_key: str) -> list[HoldoutDict]: """ Helper method to get holdouts from an applied feature flag. Args: @@ -794,40 +843,12 @@ def get_holdouts_for_flag(self, flag_key: str) -> list[Any]: Returns: The holdouts that apply for a specific flag. """ - feature_flag = self.feature_key_map.get(flag_key) - if not feature_flag: + if not self.holdouts: return [] - flag_id = feature_flag.id - - # Check cache first - if flag_id in self.flag_holdouts_map: - return self.flag_holdouts_map[flag_id] - - holdouts = [] - - # Add global holdouts that don't exclude this flag - for holdout in self.global_holdouts.values(): - is_excluded = False - excluded_flags = holdout.get('excludedFlags') - if excluded_flags: - for excluded_flag_id in excluded_flags: - if excluded_flag_id == flag_id: - is_excluded = True - break - if not is_excluded: - holdouts.append(holdout) - - # Add holdouts that specifically include this flag - if flag_id in self.included_holdouts: - holdouts.extend(self.included_holdouts[flag_id]) - - # Cache the result - self.flag_holdouts_map[flag_id] = holdouts - - return holdouts + return self.flag_holdouts_map.get(flag_key, []) - def get_holdout(self, holdout_id: str) -> Optional[dict[str, Any]]: + def get_holdout(self, holdout_id: str) -> Optional[HoldoutDict]: """ Helper method to get holdout from holdout ID. Args: diff --git a/tests/test_bucketing_holdout.py b/tests/test_bucketing_holdout.py new file mode 100644 index 000000000..e3d9bcb30 --- /dev/null +++ b/tests/test_bucketing_holdout.py @@ -0,0 +1,360 @@ +# Copyright 2025 Optimizely and contributors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +import json +from unittest import mock + +from optimizely import bucketer +from optimizely import error_handler +from optimizely import logger +from optimizely import optimizely as optimizely_module +from tests import base + + +class TestBucketer(bucketer.Bucketer): + """Helper class for testing with controlled bucket values.""" + + def __init__(self): + super().__init__() + self._bucket_values = [] + self._bucket_index = 0 + + def set_bucket_values(self, values): + """Set predetermined bucket values for testing.""" + self._bucket_values = values + self._bucket_index = 0 + + def _generate_bucket_value(self, bucketing_id): + """Override to return controlled bucket values.""" + if not self._bucket_values: + return super()._generate_bucket_value(bucketing_id) + + value = self._bucket_values[self._bucket_index] + self._bucket_index = (self._bucket_index + 1) % len(self._bucket_values) + return value + + +class BucketerHoldoutTest(base.BaseTest): + """Tests for Optimizely Bucketer with Holdouts.""" + + def setUp(self): + base.BaseTest.setUp(self) + self.error_handler = error_handler.NoOpErrorHandler() + self.mock_logger = mock.MagicMock(spec=logger.Logger) + + # Create a config dict with holdouts that have variations and traffic allocation + config_dict_with_holdouts = self.config_dict.copy() + + config_dict_with_holdouts['holdouts'] = [ + { + 'id': 'holdout_1', + 'key': 'test_holdout', + 'status': 'Running', + 'includedFlags': [], + 'excludedFlags': [], + 'audienceIds': [], + 'variations': [ + { + 'id': 'var_1', + 'key': 'control', + 'variables': [] + }, + { + 'id': 'var_2', + 'key': 'treatment', + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'var_1', + 'endOfRange': 5000 + }, + { + 'entityId': 'var_2', + 'endOfRange': 10000 + } + ] + }, + { + 'id': 'holdout_empty_1', + 'key': 'empty_holdout', + 'status': 'Running', + 'includedFlags': [], + 'excludedFlags': [], + 'audienceIds': [], + 'variations': [], + 'trafficAllocation': [] + } + ] + + # Convert to JSON and create config + config_json = json.dumps(config_dict_with_holdouts) + opt_obj = optimizely_module.Optimizely(config_json) + self.config = opt_obj.config_manager.get_config() + + self.test_bucketer = TestBucketer() + self.test_user_id = 'test_user_id' + self.test_bucketing_id = 'test_bucketing_id' + + # Verify that the config contains holdouts + self.assertIsNotNone(self.config.holdouts) + self.assertGreater(len(self.config.holdouts), 0) + + def test_bucket_user_within_valid_traffic_allocation_range(self): + """Should bucket user within valid traffic allocation range.""" + holdout = self.config.get_holdout('holdout_1') + self.assertIsNotNone(holdout) + + # Set bucket value to be within first variation's traffic allocation (0-5000 range) + self.test_bucketer.set_bucket_values([2500]) + + variation, reasons = self.test_bucketer.bucket( + self.config, holdout, self.test_user_id, self.test_bucketing_id + ) + + self.assertIsNotNone(variation) + self.assertEqual(variation['id'], 'var_1') + self.assertEqual(variation['key'], 'control') + + def test_bucket_returns_none_when_user_outside_traffic_allocation(self): + """Should return None when user is outside traffic allocation range.""" + holdout = self.config.get_holdout('holdout_1') + self.assertIsNotNone(holdout) + + # Modify traffic allocation to be smaller + modified_holdout = copy.deepcopy(holdout) + modified_holdout['trafficAllocation'] = [ + { + 'entityId': 'var_1', + 'endOfRange': 1000 + } + ] + + # Set bucket value outside traffic allocation range + self.test_bucketer.set_bucket_values([1500]) + + variation, reasons = self.test_bucketer.bucket( + self.config, modified_holdout, self.test_user_id, self.test_bucketing_id + ) + + self.assertIsNone(variation) + + def test_bucket_returns_none_when_holdout_has_no_traffic_allocation(self): + """Should return None when holdout has no traffic allocation.""" + holdout = self.config.get_holdout('holdout_1') + self.assertIsNotNone(holdout) + + # Clear traffic allocation + modified_holdout = copy.deepcopy(holdout) + modified_holdout['trafficAllocation'] = [] + + self.test_bucketer.set_bucket_values([5000]) + + variation, reasons = self.test_bucketer.bucket( + self.config, modified_holdout, self.test_user_id, self.test_bucketing_id + ) + + self.assertIsNone(variation) + + def test_bucket_returns_none_with_invalid_variation_id(self): + """Should return None when traffic allocation points to invalid variation ID.""" + holdout = self.config.get_holdout('holdout_1') + self.assertIsNotNone(holdout) + + # Set traffic allocation to point to non-existent variation + modified_holdout = copy.deepcopy(holdout) + modified_holdout['trafficAllocation'] = [ + { + 'entityId': 'invalid_variation_id', + 'endOfRange': 10000 + } + ] + + self.test_bucketer.set_bucket_values([5000]) + + variation, reasons = self.test_bucketer.bucket( + self.config, modified_holdout, self.test_user_id, self.test_bucketing_id + ) + + self.assertIsNone(variation) + + def test_bucket_returns_none_when_holdout_has_no_variations(self): + """Should return None when holdout has no variations.""" + holdout = self.config.get_holdout('holdout_empty_1') + self.assertIsNotNone(holdout) + self.assertEqual(len(holdout.get('variations', [])), 0) + + self.test_bucketer.set_bucket_values([5000]) + + variation, reasons = self.test_bucketer.bucket( + self.config, holdout, self.test_user_id, self.test_bucketing_id + ) + + self.assertIsNone(variation) + + def test_bucket_returns_none_with_empty_key(self): + """Should return None when holdout has empty key.""" + holdout = self.config.get_holdout('holdout_1') + self.assertIsNotNone(holdout) + + # Clear holdout key + modified_holdout = copy.deepcopy(holdout) + modified_holdout['key'] = '' + + self.test_bucketer.set_bucket_values([5000]) + + variation, reasons = self.test_bucketer.bucket( + self.config, modified_holdout, self.test_user_id, self.test_bucketing_id + ) + + self.assertIsNone(variation) + + def test_bucket_returns_none_with_null_key(self): + """Should return None when holdout has null key.""" + holdout = self.config.get_holdout('holdout_1') + self.assertIsNotNone(holdout) + + # Set holdout key to None + modified_holdout = copy.deepcopy(holdout) + modified_holdout['key'] = None + + self.test_bucketer.set_bucket_values([5000]) + + variation, reasons = self.test_bucketer.bucket( + self.config, modified_holdout, self.test_user_id, self.test_bucketing_id + ) + + self.assertIsNone(variation) + + def test_bucket_user_into_first_variation_with_multiple_variations(self): + """Should bucket user into first variation with multiple variations.""" + holdout = self.config.get_holdout('holdout_1') + self.assertIsNotNone(holdout) + + # Verify holdout has multiple variations + self.assertGreaterEqual(len(holdout['variations']), 2) + + # Test user buckets into first variation + self.test_bucketer.set_bucket_values([2500]) + variation, reasons = self.test_bucketer.bucket( + self.config, holdout, self.test_user_id, self.test_bucketing_id + ) + + self.assertIsNotNone(variation) + self.assertEqual(variation['id'], 'var_1') + self.assertEqual(variation['key'], 'control') + + def test_bucket_user_into_second_variation_with_multiple_variations(self): + """Should bucket user into second variation with multiple variations.""" + holdout = self.config.get_holdout('holdout_1') + self.assertIsNotNone(holdout) + + # Verify holdout has multiple variations + self.assertGreaterEqual(len(holdout['variations']), 2) + self.assertEqual(holdout['variations'][0]['id'], 'var_1') + self.assertEqual(holdout['variations'][1]['id'], 'var_2') + + # Test user buckets into second variation (bucket value 7500 should be in 5000-10000 range) + self.test_bucketer.set_bucket_values([7500]) + variation, reasons = self.test_bucketer.bucket( + self.config, holdout, self.test_user_id, self.test_bucketing_id + ) + + self.assertIsNotNone(variation) + self.assertEqual(variation['id'], 'var_2') + self.assertEqual(variation['key'], 'treatment') + + def test_bucket_handles_edge_case_boundary_values(self): + """Should handle edge case boundary values correctly.""" + holdout = self.config.get_holdout('holdout_1') + self.assertIsNotNone(holdout) + + # Modify traffic allocation to be 5000 (50%) + modified_holdout = copy.deepcopy(holdout) + modified_holdout['trafficAllocation'] = [ + { + 'entityId': 'var_1', + 'endOfRange': 5000 + } + ] + + # Test exact boundary value (should be included) + self.test_bucketer.set_bucket_values([4999]) + variation, reasons = self.test_bucketer.bucket( + self.config, modified_holdout, self.test_user_id, self.test_bucketing_id + ) + + self.assertIsNotNone(variation) + self.assertEqual(variation['id'], 'var_1') + + # Test value just outside boundary (should not be included) + self.test_bucketer.set_bucket_values([5000]) + variation, reasons = self.test_bucketer.bucket( + self.config, modified_holdout, self.test_user_id, self.test_bucketing_id + ) + + self.assertIsNone(variation) + + def test_bucket_produces_consistent_results_with_same_inputs(self): + """Should produce consistent results with same inputs.""" + holdout = self.config.get_holdout('holdout_1') + self.assertIsNotNone(holdout) + + # Create a real bucketer (not test bucketer) for consistent hashing + real_bucketer = bucketer.Bucketer() + variation1, reasons1 = real_bucketer.bucket( + self.config, holdout, self.test_user_id, self.test_bucketing_id + ) + variation2, reasons2 = real_bucketer.bucket( + self.config, holdout, self.test_user_id, self.test_bucketing_id + ) + + # Results should be identical + if variation1: + self.assertIsNotNone(variation2) + self.assertEqual(variation1['id'], variation2['id']) + self.assertEqual(variation1['key'], variation2['key']) + else: + self.assertIsNone(variation2) + + def test_bucket_handles_different_bucketing_ids_without_exceptions(self): + """Should handle different bucketing IDs without exceptions.""" + holdout = self.config.get_holdout('holdout_1') + self.assertIsNotNone(holdout) + + # Create a real bucketer (not test bucketer) for real hashing behavior + real_bucketer = bucketer.Bucketer() + + # These calls should not raise exceptions + try: + real_bucketer.bucket(self.config, holdout, self.test_user_id, 'bucketingId1') + real_bucketer.bucket(self.config, holdout, self.test_user_id, 'bucketingId2') + except Exception as e: + self.fail(f'Bucketing raised an exception: {e}') + + def test_bucket_populates_decision_reasons_properly(self): + """Should populate decision reasons properly.""" + holdout = self.config.get_holdout('holdout_1') + self.assertIsNotNone(holdout) + + self.test_bucketer.set_bucket_values([5000]) + variation, reasons = self.test_bucketer.bucket( + self.config, holdout, self.test_user_id, self.test_bucketing_id + ) + + self.assertIsNotNone(reasons) + self.assertIsInstance(reasons, list) + # Decision reasons should be populated from the bucketing process diff --git a/tests/test_decision_service_holdout.py b/tests/test_decision_service_holdout.py new file mode 100644 index 000000000..d4238218f --- /dev/null +++ b/tests/test_decision_service_holdout.py @@ -0,0 +1,568 @@ +# Copyright 2025 Optimizely and contributors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +from unittest import mock + +from optimizely import decision_service +from optimizely import error_handler +from optimizely import logger +from optimizely import optimizely as optimizely_module +from optimizely.decision.optimizely_decide_option import OptimizelyDecideOption +from optimizely.helpers import enums +from tests import base + + +class DecisionServiceHoldoutTest(base.BaseTest): + """Tests for Decision Service with Holdouts.""" + + def setUp(self): + base.BaseTest.setUp(self) + self.error_handler = error_handler.NoOpErrorHandler() + self.spy_logger = mock.MagicMock(spec=logger.SimpleLogger) + self.spy_logger.logger = self.spy_logger + self.spy_user_profile_service = mock.MagicMock() + self.spy_cmab_service = mock.MagicMock() + + # Create a config dict with holdouts and feature flags + config_dict_with_holdouts = self.config_dict_with_features.copy() + + # Get feature flag ID for test_feature_in_experiment + test_feature_id = '91111' + + config_dict_with_holdouts['holdouts'] = [ + { + 'id': 'holdout_1', + 'key': 'test_holdout', + 'status': 'Running', + 'includedFlags': [], + 'excludedFlags': [], + 'audienceIds': [], + 'variations': [ + { + 'id': 'holdout_var_1', + 'key': 'holdout_control', + 'variables': [] + }, + { + 'id': 'holdout_var_2', + 'key': 'holdout_treatment', + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'holdout_var_1', + 'endOfRange': 5000 + }, + { + 'entityId': 'holdout_var_2', + 'endOfRange': 10000 + } + ] + }, + { + 'id': 'holdout_2', + 'key': 'excluded_holdout', + 'status': 'Running', + 'includedFlags': [], + 'excludedFlags': [test_feature_id], + 'audienceIds': [], + 'variations': [ + { + 'id': 'holdout_var_3', + 'key': 'control', + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'holdout_var_3', + 'endOfRange': 10000 + } + ] + } + ] + + # Convert to JSON and create config + config_json = json.dumps(config_dict_with_holdouts) + self.opt_obj = optimizely_module.Optimizely(config_json) + self.config_with_holdouts = self.opt_obj.config_manager.get_config() + + self.decision_service_with_holdouts = decision_service.DecisionService( + self.spy_logger, + self.spy_user_profile_service, + self.spy_cmab_service + ) + + def tearDown(self): + if hasattr(self, 'opt_obj'): + self.opt_obj.close() + + # get_variations_for_feature_list with holdouts tests + + def test_holdout_active_and_user_bucketed_returns_holdout_decision(self): + """When holdout is active and user is bucketed, should return holdout decision with variation.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + holdout = self.config_with_holdouts.holdouts[0] if self.config_with_holdouts.holdouts else None + self.assertIsNotNone(holdout) + + user_context = self.opt_obj.create_user_context('testUserId', {}) + + result = self.decision_service_with_holdouts.get_variations_for_feature_list( + self.config_with_holdouts, + [feature_flag], + user_context, + [] + ) + + self.assertIsNotNone(result) + self.assertIsInstance(result, list) + self.assertGreater(len(result), 0) + + # Verify result structure is valid + for decision_result in result: + self.assertIn('decision', decision_result) + self.assertIn('reasons', decision_result) + + def test_holdout_inactive_does_not_bucket_users(self): + """When holdout is inactive, should not bucket users and log appropriate message.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + holdout = self.config_with_holdouts.holdouts[0] if self.config_with_holdouts.holdouts else None + self.assertIsNotNone(holdout) + + # Mock holdout as inactive + original_status = holdout['status'] + holdout['status'] = 'Paused' + + user_context = self.opt_obj.create_user_context('testUserId', {}) + + result = self.decision_service_with_holdouts.get_decision_for_flag( + feature_flag, + user_context, + self.config_with_holdouts + ) + + # Assert that result is not nil and has expected structure + self.assertIsNotNone(result) + self.assertIn('decision', result) + self.assertIn('reasons', result) + + # Restore original status + holdout['status'] = original_status + + def test_user_not_bucketed_into_holdout_executes_successfully(self): + """When user is not bucketed into holdout, should execute successfully with valid result structure.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + user_context = self.opt_obj.create_user_context('testUserId', {}) + + result = self.decision_service_with_holdouts.get_variations_for_feature_list( + self.config_with_holdouts, + [feature_flag], + user_context, + [] + ) + + # With real bucketer, we can't guarantee specific bucketing results + # but we can verify the method executes successfully + self.assertIsNotNone(result) + self.assertIsInstance(result, list) + + def test_holdout_with_user_attributes_for_audience_targeting(self): + """Should evaluate holdout with user attributes.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + user_attributes = { + 'browser': 'chrome', + 'location': 'us' + } + + user_context = self.opt_obj.create_user_context('testUserId', user_attributes) + + result = self.decision_service_with_holdouts.get_variations_for_feature_list( + self.config_with_holdouts, + [feature_flag], + user_context, + [] + ) + + self.assertIsNotNone(result) + self.assertIsInstance(result, list) + + def test_multiple_holdouts_for_single_feature_flag(self): + """Should handle multiple holdouts for a single feature flag.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + user_context = self.opt_obj.create_user_context('testUserId', {}) + + result = self.decision_service_with_holdouts.get_variations_for_feature_list( + self.config_with_holdouts, + [feature_flag], + user_context, + [] + ) + + self.assertIsNotNone(result) + self.assertIsInstance(result, list) + + def test_holdout_bucketing_with_empty_user_id(self): + """Should allow holdout bucketing with empty user ID.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + # Empty user ID should still be valid for bucketing + user_context = self.opt_obj.create_user_context('', {}) + + result = self.decision_service_with_holdouts.get_variations_for_feature_list( + self.config_with_holdouts, + [feature_flag], + user_context, + [] + ) + + self.assertIsNotNone(result) + + def test_holdout_populates_decision_reasons(self): + """Should populate decision reasons for holdouts.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + user_context = self.opt_obj.create_user_context('testUserId', {}) + + result = self.decision_service_with_holdouts.get_variations_for_feature_list( + self.config_with_holdouts, + [feature_flag], + user_context, + [] + ) + + self.assertIsNotNone(result) + + # Find any decision with reasons + decision_with_reasons = next( + (dr for dr in result if dr.get('reasons') and len(dr['reasons']) > 0), + None + ) + + if decision_with_reasons: + self.assertGreater(len(decision_with_reasons['reasons']), 0) + + # get_variation_for_feature with holdouts tests + + def test_user_bucketed_into_holdout_returns_before_experiments(self): + """ + When user is bucketed into holdout, should return holdout decision + before checking experiments or rollouts. + """ + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + user_context = self.opt_obj.create_user_context('testUserId', {}) + + decision_result = self.decision_service_with_holdouts.get_variation_for_feature( + self.config_with_holdouts, + feature_flag, + user_context + ) + + self.assertIsNotNone(decision_result) + + # Decision should be valid + if decision_result.get('decision'): + decision = decision_result['decision'] + self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) + self.assertIsNotNone(decision.variation) + self.assertIsNone(decision.experiment) + + def test_no_holdout_decision_falls_through_to_experiment_and_rollout(self): + """When holdout returns no decision, should fall through to experiment and rollout evaluation.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + # Use a user ID that won't be bucketed into holdout + user_context = self.opt_obj.create_user_context('non_holdout_user', {}) + + decision_result = self.decision_service_with_holdouts.get_variation_for_feature( + self.config_with_holdouts, + feature_flag, + user_context + ) + + # Should still get a valid decision result + self.assertIsNotNone(decision_result) + self.assertIn('decision', decision_result) + self.assertIn('reasons', decision_result) + + def test_holdout_respects_decision_options(self): + """Should respect decision options when evaluating holdouts.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + user_context = self.opt_obj.create_user_context('testUserId', {}) + + # Test with INCLUDE_REASONS option + decision_result = self.decision_service_with_holdouts.get_variation_for_feature( + self.config_with_holdouts, + feature_flag, + user_context, + [OptimizelyDecideOption.INCLUDE_REASONS] + ) + + self.assertIsNotNone(decision_result) + self.assertIsInstance(decision_result.get('reasons'), list) + + # Holdout priority and evaluation order tests + + def test_evaluates_holdouts_before_experiments(self): + """Should evaluate holdouts before experiments.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + user_context = self.opt_obj.create_user_context('testUserId', {}) + + decision_result = self.decision_service_with_holdouts.get_variation_for_feature( + self.config_with_holdouts, + feature_flag, + user_context + ) + + self.assertIsNotNone(decision_result) + + def test_evaluates_global_holdouts_for_all_flags(self): + """Should evaluate global holdouts for all flags.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + # Get global holdouts + global_holdouts = [ + h for h in self.config_with_holdouts.holdouts + if not h.get('includedFlags') or len(h.get('includedFlags', [])) == 0 + ] + + if global_holdouts: + user_context = self.opt_obj.create_user_context('testUserId', {}) + + result = self.decision_service_with_holdouts.get_variations_for_feature_list( + self.config_with_holdouts, + [feature_flag], + user_context, + [] + ) + + self.assertIsNotNone(result) + self.assertIsInstance(result, list) + + def test_respects_included_and_excluded_flags_configuration(self): + """Should respect included and excluded flags configuration.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + + if feature_flag: + # Get holdouts for this flag + holdouts_for_flag = self.config_with_holdouts.get_holdouts_for_flag('test_feature_in_experiment') + + # Should not include holdouts that exclude this flag + excluded_holdout = next((h for h in holdouts_for_flag if h.get('key') == 'excluded_holdout'), None) + self.assertIsNone(excluded_holdout) + + # Holdout logging and error handling tests + + def test_logs_when_holdout_evaluation_starts(self): + """Should log when holdout evaluation starts.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + user_context = self.opt_obj.create_user_context('testUserId', {}) + + self.decision_service_with_holdouts.get_variations_for_feature_list( + self.config_with_holdouts, + [feature_flag], + user_context, + [] + ) + + # Verify that logger was called + self.assertGreater(self.spy_logger.debug.call_count + self.spy_logger.info.call_count, 0) + + def test_handles_missing_holdout_configuration_gracefully(self): + """Should handle missing holdout configuration gracefully.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + # Temporarily remove holdouts + original_holdouts = self.config_with_holdouts.holdouts + self.config_with_holdouts.holdouts = [] + + user_context = self.opt_obj.create_user_context('testUserId', {}) + + result = self.decision_service_with_holdouts.get_variations_for_feature_list( + self.config_with_holdouts, + [feature_flag], + user_context, + [] + ) + + self.assertIsNotNone(result) + + # Restore original holdouts + self.config_with_holdouts.holdouts = original_holdouts + + def test_handles_invalid_holdout_data_gracefully(self): + """Should handle invalid holdout data gracefully.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + user_context = self.opt_obj.create_user_context('testUserId', {}) + + # The method should handle invalid holdout data without crashing + result = self.decision_service_with_holdouts.get_variations_for_feature_list( + self.config_with_holdouts, + [feature_flag], + user_context, + [] + ) + + self.assertIsNotNone(result) + self.assertIsInstance(result, list) + + # Holdout bucketing behavior tests + + def test_uses_consistent_bucketing_for_same_user(self): + """Should use consistent bucketing for the same user.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + user_id = 'consistent_user' + user_context1 = self.opt_obj.create_user_context(user_id, {}) + user_context2 = self.opt_obj.create_user_context(user_id, {}) + + result1 = self.decision_service_with_holdouts.get_variations_for_feature_list( + self.config_with_holdouts, + [feature_flag], + user_context1, + [] + ) + + result2 = self.decision_service_with_holdouts.get_variations_for_feature_list( + self.config_with_holdouts, + [feature_flag], + user_context2, + [] + ) + + # Same user should get consistent results + self.assertIsNotNone(result1) + self.assertIsNotNone(result2) + + if result1 and result2: + decision1 = result1[0].get('decision') + decision2 = result2[0].get('decision') + + # If both have decisions, they should match + if decision1 and decision2: + # Variation is an object, not a dict, so use attributes + var1_id = decision1.variation.id if decision1.variation else None + var2_id = decision2.variation.id if decision2.variation else None + + self.assertEqual( + var1_id, var2_id, + "User should get consistent variation across multiple calls" + ) + + def test_uses_bucketing_id_when_provided(self): + """Should use bucketing ID when provided.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + user_attributes = { + enums.ControlAttributes.BUCKETING_ID: 'custom_bucketing_id' + } + + user_context = self.opt_obj.create_user_context('testUserId', user_attributes) + + result = self.decision_service_with_holdouts.get_variations_for_feature_list( + self.config_with_holdouts, + [feature_flag], + user_context, + [] + ) + + self.assertIsNotNone(result) + self.assertIsInstance(result, list) + + def test_handles_different_traffic_allocations(self): + """Should handle different traffic allocations.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + # Test with multiple users to see varying bucketing results + users = ['user1', 'user2', 'user3', 'user4', 'user5'] + results = [] + + for user_id in users: + user_context = self.opt_obj.create_user_context(user_id, {}) + result = self.decision_service_with_holdouts.get_variations_for_feature_list( + self.config_with_holdouts, + [feature_flag], + user_context, + [] + ) + results.append(result) + + # All results should be valid + for result in results: + self.assertIsNotNone(result) + self.assertIsInstance(result, list) + + # Holdout integration with feature experiments tests + + def test_checks_holdouts_before_feature_experiments(self): + """Should check holdouts before feature experiments.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + user_context = self.opt_obj.create_user_context('testUserId', {}) + + decision_result = self.decision_service_with_holdouts.get_variation_for_feature( + self.config_with_holdouts, + feature_flag, + user_context + ) + + self.assertIsNotNone(decision_result) + + def test_falls_back_to_experiments_if_no_holdout_decision(self): + """Should fall back to experiments if no holdout decision.""" + feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + user_context = self.opt_obj.create_user_context('non_holdout_user_123', {}) + + decision_result = self.decision_service_with_holdouts.get_variation_for_feature( + self.config_with_holdouts, + feature_flag, + user_context + ) + + # Should return a valid decision result + self.assertIsNotNone(decision_result) + self.assertIn('decision', decision_result) + self.assertIn('reasons', decision_result) From 1225cfbf5e970de1e9689d3edef5e2d54a23fd69 Mon Sep 17 00:00:00 2001 From: Farhan Anjum Date: Fri, 14 Nov 2025 02:01:04 +0600 Subject: [PATCH 06/32] [FSSDK-11958] chore: Release v5.3.0 (#468) --- CHANGELOG.md | 59 +++++++++++++++++++++++++++++++++++++++++++ optimizely/version.py | 2 +- 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d0cd8b719..807fa2424 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,64 @@ # Optimizely Python SDK Changelog +## 5.3.0 +November 13th, 2025 + +This release introduces **Contextual Multi-Armed Bandit (CMAB)** support in the Optimizely Python SDK along with several enhancements, bug fixes, and infrastructure improvements. + +--- + +### New Features + +#### **CMAB Support** + +A major addition in this release is support for **Contextual Multi-Armed Bandit (CMAB)**, enabling adaptive experimentation based on contextual user data. + +The CMAB feature includes: + +- CMAB Client and Service implementations to communicate with CMAB APIs ([#453](https://github.com/optimizely/python-sdk/pull/453), [#455](https://github.com/optimizely/python-sdk/pull/455)) +- Decision Service updates to handle CMAB-based decisioning ([#457](https://github.com/optimizely/python-sdk/pull/457)) +- Impression event updates to include CMAB UUID ([#458](https://github.com/optimizely/python-sdk/pull/458)) +- Cache system enhancements including a new `remove()` method for CMAB cache ([#454](https://github.com/optimizely/python-sdk/pull/454)) +- Configuration options to customize CMAB cache parameters ([#463](https://github.com/optimizely/python-sdk/pull/463)) +- Exposure of CMAB prediction endpoint for programmatic access ([#466](https://github.com/optimizely/python-sdk/pull/466)) + +These updates collectively enable Python SDK users to leverage machine learning–driven bandit optimization strategies within Optimizely Feature Experimentation. + +--- + +#### **Multi-Region Data Hosting** + +- Added SDK support for multi-region data hosting, allowing projects to specify their data residency region ([#459](https://github.com/optimizely/python-sdk/pull/459)). + +--- + +### Security Fixes + +- Addressed a CSRF security warning by properly importing and registering `CSRFProtect` + ([#448](https://github.com/optimizely/python-sdk/pull/448), [#450](https://github.com/optimizely/python-sdk/pull/450), [#452](https://github.com/optimizely/python-sdk/pull/452)). + +--- + +### Enhancements + +- Updated project configuration to track CMAB properties ([#451](https://github.com/optimizely/python-sdk/pull/451)). +- Removed unused `testapp` folder from tests as part of maintenance cleanup ([#461](https://github.com/optimizely/python-sdk/pull/461)). + +--- + +### Bug Fixes + +- Fixed concurrency issues in CMAB service to ensure thread-safe cache and decision logic ([#462](https://github.com/optimizely/python-sdk/pull/462)). + +--- + +### New Contributors + +- [@esrakartalOpt](https://github.com/esrakartalOpt) made their first contribution in [#459](https://github.com/optimizely/python-sdk/pull/459). + +--- + + ## 5.2.0 February 26, 2025 diff --git a/optimizely/version.py b/optimizely/version.py index 4f0f20c64..eea99d940 100644 --- a/optimizely/version.py +++ b/optimizely/version.py @@ -11,5 +11,5 @@ # See the License for the specific language governing permissions and # limitations under the License. -version_info = (5, 2, 0) +version_info = (5, 3, 0) __version__ = '.'.join(str(v) for v in version_info) From 53421a63564addc8eafb8b9d32d0a0ba52d73463 Mon Sep 17 00:00:00 2001 From: esrakartalOpt <102107327+esrakartalOpt@users.noreply.github.com> Date: Wed, 19 Nov 2025 08:04:32 -0600 Subject: [PATCH 07/32] [FSSDK-11572] Python: Update impression event handling and send notification for global holdout (#469) * [FSSDK-11572] Python: Update impression event handling and send notification for global holdout * Implement suggested comments --- optimizely/optimizely.py | 2 +- tests/test_decision_service_holdout.py | 366 ++++++++++++++++++++++++- 2 files changed, 356 insertions(+), 12 deletions(-) diff --git a/optimizely/optimizely.py b/optimizely/optimizely.py index b4c281ed1..7b27d8494 100644 --- a/optimizely/optimizely.py +++ b/optimizely/optimizely.py @@ -453,7 +453,7 @@ def _get_feature_variable_for_type( f'Returning default value for variable "{variable_key}" of feature flag "{feature_key}".' ) - if decision.source == enums.DecisionSources.FEATURE_TEST: + if decision.source in (enums.DecisionSources.FEATURE_TEST, enums.DecisionSources.HOLDOUT): source_info = { 'experiment_key': decision.experiment.key if decision.experiment else None, 'variation_key': self._get_variation_key(decision.variation), diff --git a/tests/test_decision_service_holdout.py b/tests/test_decision_service_holdout.py index d4238218f..0f47e9975 100644 --- a/tests/test_decision_service_holdout.py +++ b/tests/test_decision_service_holdout.py @@ -278,20 +278,49 @@ def test_user_bucketed_into_holdout_returns_before_experiments(self): user_context = self.opt_obj.create_user_context('testUserId', {}) - decision_result = self.decision_service_with_holdouts.get_variation_for_feature( - self.config_with_holdouts, - feature_flag, - user_context + # Mock get_holdouts_for_flag to return holdouts + holdout = self.config_with_holdouts.holdouts[0] if self.config_with_holdouts.holdouts else None + self.assertIsNotNone(holdout) + + holdout_variation = holdout['variations'][0] + + # Create a holdout decision + mock_holdout_decision = decision_service.Decision( + experiment=holdout, + variation=holdout_variation, + source=enums.DecisionSources.HOLDOUT, + cmab_uuid=None ) - self.assertIsNotNone(decision_result) + mock_holdout_result = { + 'decision': mock_holdout_decision, + 'error': False, + 'reasons': [] + } - # Decision should be valid - if decision_result.get('decision'): - decision = decision_result['decision'] - self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) - self.assertIsNotNone(decision.variation) - self.assertIsNone(decision.experiment) + # Mock get_holdouts_for_flag to return holdouts so the holdout path is taken + with mock.patch.object( + self.config_with_holdouts, + 'get_holdouts_for_flag', + return_value=[holdout] + ): + with mock.patch.object( + self.opt_obj.decision_service, + 'get_variation_for_holdout', + return_value=mock_holdout_result + ): + decision_result = self.opt_obj.decision_service.get_variation_for_feature( + self.config_with_holdouts, + feature_flag, + user_context + ) + + self.assertIsNotNone(decision_result) + + # Decision should be valid and from holdout + decision = decision_result['decision'] + self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) + self.assertIsNotNone(decision.variation) def test_no_holdout_decision_falls_through_to_experiment_and_rollout(self): """When holdout returns no decision, should fall through to experiment and rollout evaluation.""" @@ -566,3 +595,318 @@ def test_falls_back_to_experiments_if_no_holdout_decision(self): self.assertIsNotNone(decision_result) self.assertIn('decision', decision_result) self.assertIn('reasons', decision_result) + + # Holdout Impression Events tests + + def test_decide_with_holdout_sends_impression_event(self): + """Should send impression event for holdout decision.""" + # Create optimizely instance with mocked event processor + spy_event_processor = mock.MagicMock() + + config_dict_with_holdouts = self.config_dict_with_features.copy() + config_dict_with_holdouts['holdouts'] = [ + { + 'id': 'holdout_1', + 'key': 'test_holdout', + 'status': 'Running', + 'includedFlags': [], + 'excludedFlags': [], + 'audienceIds': [], + 'variations': [ + { + 'id': 'holdout_var_1', + 'key': 'holdout_control', + 'featureEnabled': True, + 'variables': [] + }, + { + 'id': 'holdout_var_2', + 'key': 'holdout_treatment', + 'featureEnabled': False, + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'holdout_var_1', + 'endOfRange': 5000 + }, + { + 'entityId': 'holdout_var_2', + 'endOfRange': 10000 + } + ] + } + ] + + config_json = json.dumps(config_dict_with_holdouts) + opt_with_mocked_events = optimizely_module.Optimizely( + datafile=config_json, + logger=self.spy_logger, + error_handler=self.error_handler, + event_processor=spy_event_processor + ) + + try: + # Use a specific user ID that will be bucketed into a holdout + test_user_id = 'user_bucketed_into_holdout' + + config = opt_with_mocked_events.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag, "Feature flag 'test_feature_in_experiment' should exist") + + user_attributes = {} + + user_context = opt_with_mocked_events.create_user_context(test_user_id, user_attributes) + decision = user_context.decide(feature_flag.key) + + self.assertIsNotNone(decision, 'Decision should not be None') + + # Find the actual holdout if this is a holdout decision + actual_holdout = None + if config.holdouts and decision.rule_key: + actual_holdout = next( + (h for h in config.holdouts if h.get('key') == decision.rule_key), + None + ) + + # Only continue if this is a holdout decision + if actual_holdout: + self.assertEqual(decision.flag_key, feature_flag.key) + + holdout_variation = next( + (v for v in actual_holdout['variations'] if v.get('key') == decision.variation_key), + None + ) + + self.assertIsNotNone( + holdout_variation, + f"Variation '{decision.variation_key}' should be from the chosen holdout '{actual_holdout['key']}'" + ) + + self.assertEqual( + decision.enabled, + holdout_variation.get('featureEnabled'), + "Enabled flag should match holdout variation's featureEnabled value" + ) + + # Verify impression event was sent + self.assertGreater(spy_event_processor.process.call_count, 0) + + # Verify impression event contains correct user details + call_args_list = spy_event_processor.process.call_args_list + user_event_found = False + for call_args in call_args_list: + if call_args[0]: # Check positional args + user_event = call_args[0][0] + if hasattr(user_event, 'user_id') and user_event.user_id == test_user_id: + user_event_found = True + break + + self.assertTrue(user_event_found, 'Impression event should contain correct user ID') + finally: + opt_with_mocked_events.close() + + def test_decide_with_holdout_does_not_send_impression_when_disabled(self): + """Should not send impression event when DISABLE_DECISION_EVENT option is used.""" + # Create optimizely instance with mocked event processor + spy_event_processor = mock.MagicMock() + + config_dict_with_holdouts = self.config_dict_with_features.copy() + config_dict_with_holdouts['holdouts'] = [ + { + 'id': 'holdout_1', + 'key': 'test_holdout', + 'status': 'Running', + 'includedFlags': [], + 'excludedFlags': [], + 'audienceIds': [], + 'variations': [ + { + 'id': 'holdout_var_1', + 'key': 'holdout_control', + 'featureEnabled': True, + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'holdout_var_1', + 'endOfRange': 10000 + } + ] + } + ] + + config_json = json.dumps(config_dict_with_holdouts) + opt_with_mocked_events = optimizely_module.Optimizely( + datafile=config_json, + logger=self.spy_logger, + error_handler=self.error_handler, + event_processor=spy_event_processor + ) + + try: + test_user_id = 'user_bucketed_into_holdout' + + config = opt_with_mocked_events.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + user_attributes = {} + + user_context = opt_with_mocked_events.create_user_context(test_user_id, user_attributes) + decision = user_context.decide( + feature_flag.key, + [OptimizelyDecideOption.DISABLE_DECISION_EVENT] + ) + + self.assertIsNotNone(decision, 'Decision should not be None') + + # Find the chosen holdout if this is a holdout decision + chosen_holdout = None + if config.holdouts and decision.rule_key: + chosen_holdout = next( + (h for h in config.holdouts if h.get('key') == decision.rule_key), + None + ) + + if chosen_holdout: + self.assertEqual(decision.flag_key, feature_flag.key) + + # Verify no impression event was sent + spy_event_processor.process.assert_not_called() + finally: + opt_with_mocked_events.close() + + def test_decide_with_holdout_sends_correct_notification_content(self): + """Should send correct notification content for holdout decision.""" + captured_notifications = [] + + def notification_callback(notification_type, user_id, user_attributes, decision_info): + captured_notifications.append(decision_info.copy()) + + config_dict_with_holdouts = self.config_dict_with_features.copy() + config_dict_with_holdouts['holdouts'] = [ + { + 'id': 'holdout_1', + 'key': 'test_holdout', + 'status': 'Running', + 'includedFlags': [], + 'excludedFlags': [], + 'audienceIds': [], + 'variations': [ + { + 'id': 'holdout_var_1', + 'key': 'holdout_control', + 'featureEnabled': True, + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'holdout_var_1', + 'endOfRange': 10000 + } + ] + } + ] + + config_json = json.dumps(config_dict_with_holdouts) + opt_with_mocked_events = optimizely_module.Optimizely( + datafile=config_json, + logger=self.spy_logger, + error_handler=self.error_handler + ) + + try: + opt_with_mocked_events.notification_center.add_notification_listener( + enums.NotificationTypes.DECISION, + notification_callback + ) + + test_user_id = 'holdout_test_user' + config = opt_with_mocked_events.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + holdout = config.holdouts[0] if config.holdouts else None + self.assertIsNotNone(holdout, 'Should have at least one holdout configured') + + holdout_variation = holdout['variations'][0] + self.assertIsNotNone(holdout_variation, 'Holdout should have at least one variation') + + mock_experiment = mock.MagicMock() + mock_experiment.key = holdout['key'] + mock_experiment.id = holdout['id'] + + # Mock the decision service to return a holdout decision + holdout_decision = decision_service.Decision( + experiment=mock_experiment, + variation=holdout_variation, + source=enums.DecisionSources.HOLDOUT, + cmab_uuid=None + ) + + holdout_decision_result = { + 'decision': holdout_decision, + 'error': False, + 'reasons': [] + } + + # Mock get_variations_for_feature_list to return holdout decision + with mock.patch.object( + opt_with_mocked_events.decision_service, + 'get_variations_for_feature_list', + return_value=[holdout_decision_result] + ): + user_context = opt_with_mocked_events.create_user_context(test_user_id, {}) + decision = user_context.decide(feature_flag.key) + + self.assertIsNotNone(decision, 'Decision should not be None') + self.assertEqual(len(captured_notifications), 1, 'Should have captured exactly one decision notification') + + notification = captured_notifications[0] + rule_key = notification.get('rule_key') + + self.assertEqual(rule_key, holdout['key'], 'RuleKey should match holdout key') + + # Verify holdout notification structure + self.assertIn('flag_key', notification, 'Holdout notification should contain flag_key') + self.assertIn('enabled', notification, 'Holdout notification should contain enabled flag') + self.assertIn('variation_key', notification, 'Holdout notification should contain variation_key') + self.assertIn('experiment_id', notification, 'Holdout notification should contain experiment_id') + self.assertIn('variation_id', notification, 'Holdout notification should contain variation_id') + + flag_key = notification.get('flag_key') + self.assertEqual(flag_key, 'test_feature_in_experiment', 'FlagKey should match the requested flag') + + experiment_id = notification.get('experiment_id') + self.assertEqual(experiment_id, holdout['id'], 'ExperimentId in notification should match holdout ID') + + variation_id = notification.get('variation_id') + self.assertEqual(variation_id, holdout_variation['id'], 'VariationId should match holdout variation ID') + + variation_key = notification.get('variation_key') + self.assertEqual( + variation_key, + holdout_variation['key'], + 'VariationKey in notification should match holdout variation key' + ) + + enabled = notification.get('enabled') + self.assertIsNotNone(enabled, 'Enabled flag should be present in notification') + self.assertEqual( + enabled, + holdout_variation.get('featureEnabled'), + "Enabled flag should match holdout variation's featureEnabled value" + ) + + self.assertIn(flag_key, config.feature_key_map, f"FlagKey '{flag_key}' should exist in config") + + self.assertIn('variables', notification, 'Notification should contain variables') + self.assertIn('reasons', notification, 'Notification should contain reasons') + self.assertIn( + 'decision_event_dispatched', notification, + 'Notification should contain decision_event_dispatched' + ) + finally: + opt_with_mocked_events.close() From 1f87f42aab710ebe84fef882d830cf67218f5d17 Mon Sep 17 00:00:00 2001 From: esrakartalOpt <102107327+esrakartalOpt@users.noreply.github.com> Date: Fri, 19 Dec 2025 08:48:12 -0600 Subject: [PATCH 08/32] [FSSDK-12094] Fix Python holdout implementation which related to FSC failures (#471) * [FSSDK-12094] Fix Ruby holdout implementation which related to FSC failures * Fix tests * Fix unit and FSC * Fix unit and FSC tests * Fix type check problems * Implement Ruby changes correctly * Fix FSC * Revert unnecessary changes * Fix FSC * Fix FSC holdout test cases * Please pass FSC * Implement holdout correctly and fix tests * Implement changes from Muzahid PR * Implement comment * Fix the cast error * Remove "layerId" --- .github/workflows/python.yml | 9 +- optimizely/bucketer.py | 114 ++--- optimizely/decision_service.py | 261 +++++------ optimizely/entities.py | 75 ++++ optimizely/event/event_factory.py | 6 +- optimizely/event/user_event.py | 7 +- optimizely/event/user_event_factory.py | 11 +- optimizely/optimizely.py | 16 +- optimizely/project_config.py | 146 +++--- tests/test_config.py | 13 +- tests/test_decision_service_holdout.py | 594 ++++++++++++++++++++++++- 11 files changed, 959 insertions(+), 293 deletions(-) diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 6baa2c09c..24d95e6a0 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -91,10 +91,11 @@ jobs: fail-fast: false matrix: python-version: - - "pypy-3.9" - - "pypy-3.10" - - "3.9" - - "3.10" + # disabled due to librt is not available on this pypy version + # - "pypy-3.9" + # - "pypy-3.10" + # - "3.9" + # - "3.10" - "3.11" - "3.12" steps: diff --git a/optimizely/bucketer.py b/optimizely/bucketer.py index ca4310126..d1e0b047c 100644 --- a/optimizely/bucketer.py +++ b/optimizely/bucketer.py @@ -12,7 +12,7 @@ # limitations under the License. from __future__ import annotations -from typing import Optional, TYPE_CHECKING +from typing import Optional, TYPE_CHECKING, cast import math from sys import version_info @@ -28,7 +28,7 @@ if TYPE_CHECKING: # prevent circular dependenacy by skipping import at runtime from .project_config import ProjectConfig - from .entities import Experiment, Variation + from .entities import Experiment, Variation, Holdout from .helpers.types import TrafficAllocation @@ -104,8 +104,8 @@ def find_bucket( def bucket( self, project_config: ProjectConfig, - experiment: Experiment, user_id: str, bucketing_id: str - ) -> tuple[Optional[Variation], list[str]]: + experiment: Experiment | Holdout, user_id: str, bucketing_id: str + ) -> tuple[Variation | None, list[str]]: """ For a given experiment and bucketing ID determines variation to be shown to user. Args: @@ -125,14 +125,9 @@ def bucket( project_config.logger.debug(message) return None, [] - if isinstance(experiment, dict): - # This is a holdout dictionary - experiment_key = experiment.get('key', '') - experiment_id = experiment.get('id', '') - else: - # This is an Experiment object - experiment_key = experiment.key - experiment_id = experiment.id + # Handle both Experiment and Holdout entities + experiment_key = experiment.key + experiment_id = experiment.id if not experiment_key or not experiment_key.strip(): message = 'Invalid entity key provided for bucketing. Returning nil.' @@ -141,14 +136,9 @@ def bucket( variation_id, decide_reasons = self.bucket_to_entity_id(project_config, experiment, user_id, bucketing_id) if variation_id: - if isinstance(experiment, dict): - # For holdouts, find the variation in the holdout's variations array - variations = experiment.get('variations', []) - variation = next((v for v in variations if v.get('id') == variation_id), None) - else: - # For experiments, use the existing method - variation = project_config.get_variation_from_id_by_experiment_id(experiment_id, variation_id) - return variation, decide_reasons + variation = project_config.get_variation_from_id_by_experiment_id(experiment_id, variation_id) + # Cast is safe here because experiments always use Variation entities, not VariationDict + return cast('Optional[Variation]', variation), decide_reasons # No variation found - log message for empty traffic range message = 'Bucketed into an empty traffic range. Returning nil.' @@ -158,7 +148,7 @@ def bucket( def bucket_to_entity_id( self, project_config: ProjectConfig, - experiment: Experiment, user_id: str, bucketing_id: str + experiment: Experiment | Holdout, user_id: str, bucketing_id: str ) -> tuple[Optional[str], list[str]]: """ For a given experiment and bucketing ID determines variation ID to be shown to user. @@ -176,58 +166,52 @@ def bucket_to_entity_id( if not experiment: return None, decide_reasons - # Handle both Experiment objects and holdout dictionaries - if isinstance(experiment, dict): - # This is a holdout dictionary - holdouts don't have groups - experiment_key = experiment.get('key', '') - experiment_id = experiment.get('id', '') - traffic_allocations = experiment.get('trafficAllocation', []) - has_cmab = False - group_policy = None - else: - # This is an Experiment object - experiment_key = experiment.key - experiment_id = experiment.id - traffic_allocations = experiment.trafficAllocation - has_cmab = bool(experiment.cmab) + # Handle both Experiment and Holdout entities + # Both entities have key, id, and trafficAllocation attributes + from . import entities + + experiment_key = experiment.key + experiment_id = experiment.id + traffic_allocations = experiment.trafficAllocation + + # Determine if experiment is in a mutually exclusive group + # Holdouts don't have groupId or groupPolicy - use isinstance for type narrowing + if isinstance(experiment, entities.Experiment): group_policy = getattr(experiment, 'groupPolicy', None) + if group_policy and group_policy in GROUP_POLICIES: + group = project_config.get_group(experiment.groupId) - # Determine if experiment is in a mutually exclusive group. - # This will not affect evaluation of rollout rules or holdouts. - if group_policy and group_policy in GROUP_POLICIES: - group = project_config.get_group(experiment.groupId) + if not group: + return None, decide_reasons - if not group: - return None, decide_reasons + user_experiment_id = self.find_bucket( + project_config, bucketing_id, experiment.groupId, group.trafficAllocation, + ) - user_experiment_id = self.find_bucket( - project_config, bucketing_id, experiment.groupId, group.trafficAllocation, - ) + if not user_experiment_id: + message = f'User "{user_id}" is in no experiment.' + project_config.logger.info(message) + decide_reasons.append(message) + return None, decide_reasons - if not user_experiment_id: - message = f'User "{user_id}" is in no experiment.' - project_config.logger.info(message) - decide_reasons.append(message) - return None, decide_reasons + if user_experiment_id != experiment_id: + message = f'User "{user_id}" is not in experiment "{experiment_key}" of group {experiment.groupId}.' + project_config.logger.info(message) + decide_reasons.append(message) + return None, decide_reasons - if user_experiment_id != experiment_id: - message = f'User "{user_id}" is not in experiment "{experiment_key}" of group {experiment.groupId}.' + message = f'User "{user_id}" is in experiment {experiment_key} of group {experiment.groupId}.' project_config.logger.info(message) decide_reasons.append(message) - return None, decide_reasons - - message = f'User "{user_id}" is in experiment {experiment_key} of group {experiment.groupId}.' - project_config.logger.info(message) - decide_reasons.append(message) - - if has_cmab: - if experiment.cmab: - traffic_allocations = [ - { - "entityId": "$", - "endOfRange": experiment.cmab['trafficAllocation'] - } - ] + + # Holdouts don't have cmab - use isinstance for type narrowing + if isinstance(experiment, entities.Experiment) and experiment.cmab: + traffic_allocations = [ + { + "entityId": "$", + "endOfRange": experiment.cmab['trafficAllocation'] + } + ] # Bucket user if not in white-list and in group (if any) variation_id = self.find_bucket(project_config, bucketing_id, diff --git a/optimizely/decision_service.py b/optimizely/decision_service.py index 78be89d8e..28275ef65 100644 --- a/optimizely/decision_service.py +++ b/optimizely/decision_service.py @@ -14,7 +14,7 @@ from __future__ import annotations from typing import TYPE_CHECKING, NamedTuple, Optional, Sequence, List, TypedDict, Union -from optimizely.helpers.types import HoldoutDict, VariationDict +from optimizely.helpers.types import VariationDict from . import bucketer from . import entities @@ -81,7 +81,7 @@ class DecisionResult(TypedDict): class Decision(NamedTuple): """Named tuple containing selected experiment, variation, source and cmab_uuid. None if no experiment/variation was selected.""" - experiment: Optional[entities.Experiment] + experiment: Optional[Union[entities.Experiment, entities.Holdout]] variation: Optional[Union[entities.Variation, VariationDict]] source: Optional[str] cmab_uuid: Optional[str] @@ -246,7 +246,11 @@ def set_forced_variation( # The invalid variation key will be logged inside this call. return False - variation_id = forced_variation.id + # Handle both Variation entity and VariationDict + if isinstance(forced_variation, dict): + variation_id = forced_variation['id'] + else: + variation_id = forced_variation.id if user_id not in self.forced_variation_map: self.forced_variation_map[user_id] = {experiment_id: variation_id} @@ -261,7 +265,7 @@ def set_forced_variation( def get_forced_variation( self, project_config: ProjectConfig, experiment_key: str, user_id: str - ) -> tuple[Optional[entities.Variation], list[str]]: + ) -> tuple[Optional[Union[entities.Variation, VariationDict]], list[str]]: """ Gets the forced variation key for the given user and experiment. Args: @@ -302,7 +306,9 @@ def get_forced_variation( if variation is None: return None, decide_reasons - message = f'Variation "{variation.key}" is mapped to experiment "{experiment_key}" and ' \ + # Handle both Variation entity and VariationDict + var_key = variation['key'] if isinstance(variation, dict) else variation.key + message = f'Variation "{var_key}" is mapped to experiment "{experiment_key}" and ' \ f'user "{user_id}" in the forced variation map' self.logger.debug(message) decide_reasons.append(message) @@ -310,7 +316,7 @@ def get_forced_variation( def get_whitelisted_variation( self, project_config: ProjectConfig, experiment: entities.Experiment, user_id: str - ) -> tuple[Optional[entities.Variation], list[str]]: + ) -> tuple[Optional[Union[entities.Variation, VariationDict]], list[str]]: """ Determine if a user is forced into a variation (through whitelisting) for the given experiment and return that variation. @@ -341,7 +347,7 @@ def get_whitelisted_variation( def get_stored_variation( self, project_config: ProjectConfig, experiment: entities.Experiment, user_profile: UserProfile - ) -> Optional[entities.Variation]: + ) -> Optional[Union[entities.Variation, VariationDict]]: """ Determine if the user has a stored variation available for the given experiment and return that. Args: @@ -358,8 +364,10 @@ def get_stored_variation( if variation_id: variation = project_config.get_variation_from_id(experiment.key, variation_id) if variation: + # Handle both Variation entity and VariationDict + var_key = variation['key'] if isinstance(variation, dict) else variation.key message = f'Found a stored decision. User "{user_id}" is in ' \ - f'variation "{variation.key}" of experiment "{experiment.key}".' + f'variation "{var_key}" of experiment "{experiment.key}".' self.logger.info(message) return variation @@ -426,7 +434,7 @@ def get_variation( } # Check if the user is forced into a variation - variation: Optional[entities.Variation] + variation: Optional[Union[entities.Variation, VariationDict]] variation, reasons_received = self.get_forced_variation(project_config, experiment.key, user_id) decide_reasons += reasons_received if variation: @@ -672,13 +680,26 @@ def get_variation_for_feature( - 'error': Boolean indicating if an error occurred during the decision process. - 'reasons': List of log messages representing decision making for the feature. """ - holdouts = project_config.get_holdouts_for_flag(feature.key) - - if holdouts: - # Has holdouts - use get_decision_for_flag which checks holdouts first - return self.get_decision_for_flag(feature, user_context, project_config, options) + # Check if user profile service should be ignored + if options: + ignore_ups = OptimizelyDecideOption.IGNORE_USER_PROFILE_SERVICE in options else: - return self.get_variations_for_feature_list(project_config, [feature], user_context, options)[0] + ignore_ups = False + + # Create user profile tracker for sticky bucketing + user_profile_tracker: Optional[UserProfileTracker] = None + if self.user_profile_service is not None and not ignore_ups: + user_profile_tracker = UserProfileTracker(user_context.user_id, self.user_profile_service, self.logger) + # Load user profile once before processing + user_profile_tracker.load_user_profile([], None) + + result = self.get_decision_for_flag(feature, user_context, project_config, options, user_profile_tracker) + + # Save user profile after decision + if user_profile_tracker is not None and not ignore_ups: + user_profile_tracker.save_user_profile() + + return result def get_decision_for_flag( self, @@ -719,7 +740,7 @@ def get_decision_for_flag( continue message = ( - f"The user '{user_id}' is bucketed into holdout '{holdout['key']}' " + f"The user '{user_id}' is bucketed into holdout '{holdout.key}' " f"for feature flag '{feature_flag.key}'." ) self.logger.info(message) @@ -730,25 +751,82 @@ def get_decision_for_flag( 'reasons': reasons } - # If no holdout decision, fall back to existing experiment/rollout logic - # Use get_variations_for_feature_list which handles experiments and rollouts - fallback_result = self.get_variations_for_feature_list( - project_config, [feature_flag], user_context, decide_options - )[0] + # If no holdout decision, check experiments then rollouts + if feature_flag.experimentIds: + for experiment_id in feature_flag.experimentIds: + experiment = project_config.get_experiment_from_id(experiment_id) + + if experiment: + # Check for forced decision + optimizely_decision_context = OptimizelyUserContext.OptimizelyDecisionContext( + feature_flag.key, experiment.key) + forced_decision_variation, forced_reasons = self.validated_forced_decision( + project_config, optimizely_decision_context, user_context) + reasons.extend(forced_reasons) + + if forced_decision_variation: + decision = Decision(experiment, forced_decision_variation, + enums.DecisionSources.FEATURE_TEST, None) + return { + 'decision': decision, + 'error': False, + 'reasons': reasons + } + + # Get variation for experiment + variation_result = self.get_variation( + project_config, experiment, user_context, user_profile_tracker, reasons, decide_options + ) + reasons.extend(variation_result['reasons']) + + if variation_result['error']: + decision = Decision(experiment, None, enums.DecisionSources.FEATURE_TEST, + variation_result['cmab_uuid']) + return { + 'decision': decision, + 'error': True, + 'reasons': reasons + } + + if variation_result['variation']: + decision = Decision(experiment, variation_result['variation'], + enums.DecisionSources.FEATURE_TEST, + variation_result['cmab_uuid']) + return { + 'decision': decision, + 'error': False, + 'reasons': reasons + } + + # If no experiment decision, check rollouts + rollout_decision, rollout_reasons = self.get_variation_for_rollout( + project_config, feature_flag, user_context + ) + if rollout_reasons: + reasons.extend(rollout_reasons) + + # Log rollout decision for backward compatibility with tests + has_variation = False + if isinstance(rollout_decision, Decision): + has_variation = rollout_decision.variation is not None + else: + # Handle mocked return values in tests + has_variation = rollout_decision is not None - # Merge reasons - if fallback_result.get('reasons'): - reasons.extend(fallback_result['reasons']) + if has_variation: + self.logger.debug(f'User "{user_id}" bucketed into rollout for feature "{feature_flag.key}".') + else: + self.logger.debug(f'User "{user_id}" not bucketed into any rollout for feature "{feature_flag.key}".') return { - 'decision': fallback_result['decision'], - 'error': fallback_result.get('error', False), + 'decision': rollout_decision, + 'error': False, 'reasons': reasons } def get_variation_for_holdout( self, - holdout: HoldoutDict, + holdout: entities.Holdout, user_context: OptimizelyUserContext, project_config: ProjectConfig ) -> DecisionResult: @@ -756,7 +834,7 @@ def get_variation_for_holdout( Get the variation for holdout. Args: - holdout: The holdout configuration (HoldoutDict). + holdout: The holdout configuration (Holdout entity). user_context: The user context. project_config: The project config. @@ -769,9 +847,9 @@ def get_variation_for_holdout( user_id = user_context.user_id attributes = user_context.get_user_attributes() - if not holdout or not holdout.get('status') or holdout.get('status') != 'Running': - key = holdout.get('key') if holdout else 'unknown' - message = f"Holdout '{key}' is not running." + # Check if holdout is activated (Running status) + if not holdout.is_activated: + message = f"Holdout '{holdout.key}' is not running." self.logger.info(message) decide_reasons.append(message) return { @@ -783,13 +861,13 @@ def get_variation_for_holdout( bucketing_id, bucketing_id_reasons = self._get_bucketing_id(user_id, attributes) decide_reasons.extend(bucketing_id_reasons) - # Check audience conditions - audience_conditions = holdout.get('audienceIds') + # Check audience conditions using the same method as experiments + audience_conditions = holdout.get_audience_conditions_or_ids() user_meets_audience_conditions, reasons_received = audience_helper.does_user_meet_audience_conditions( project_config, audience_conditions, ExperimentAudienceEvaluationLogs, - holdout.get('key', 'unknown'), + holdout.key, user_context, self.logger ) @@ -798,7 +876,7 @@ def get_variation_for_holdout( if not user_meets_audience_conditions: message = ( f"User '{user_id}' does not meet the conditions for holdout " - f"'{holdout['key']}'." + f"'{holdout.key}'." ) self.logger.debug(message) decide_reasons.append(message) @@ -810,23 +888,21 @@ def get_variation_for_holdout( # Bucket user into holdout variation variation, bucket_reasons = self.bucketer.bucket( - project_config, holdout, user_id, bucketing_id # type: ignore[arg-type] + project_config, holdout, user_id, bucketing_id ) decide_reasons.extend(bucket_reasons) if variation: - # For holdouts, variation is a dict, not a Variation entity - variation_key = variation['key'] if isinstance(variation, dict) else variation.key + variation_key = variation.get('key') if isinstance(variation, dict) else variation.key message = ( f"The user '{user_id}' is bucketed into variation '{variation_key}' " - f"of holdout '{holdout['key']}'." + f"of holdout '{holdout.key}'." ) self.logger.info(message) decide_reasons.append(message) - # Create Decision for holdout - experiment is None, source is HOLDOUT holdout_decision: Decision = Decision( - experiment=None, + experiment=holdout, variation=variation, source=enums.DecisionSources.HOLDOUT, cmab_uuid=None @@ -837,7 +913,7 @@ def get_variation_for_holdout( 'reasons': decide_reasons } - message = f"User '{user_id}' is not bucketed into any variation for holdout '{holdout['key']}'." + message = f"User '{user_id}' is not bucketed into any variation for holdout '{holdout.key}'." self.logger.info(message) decide_reasons.append(message) return { @@ -931,100 +1007,37 @@ def get_variations_for_feature_list( - 'error': Boolean indicating if an error occurred during the decision process. - 'reasons': List of log messages representing decision making for each feature. """ - decide_reasons: list[str] = [] + user_id = user_context.user_id + # Check if user profile service should be ignored if options: ignore_ups = OptimizelyDecideOption.IGNORE_USER_PROFILE_SERVICE in options else: ignore_ups = False + # Create user profile tracker once for all features user_profile_tracker: Optional[UserProfileTracker] = None if self.user_profile_service is not None and not ignore_ups: - user_profile_tracker = UserProfileTracker(user_context.user_id, self.user_profile_service, self.logger) - user_profile_tracker.load_user_profile(decide_reasons, None) + user_profile_tracker = UserProfileTracker(user_id, self.user_profile_service, self.logger) + # Load user profile once before processing features + user_profile_tracker.load_user_profile([], None) - decisions = [] + # Process each feature by delegating to get_decision_for_flag + decisions: list[DecisionResult] = [] for feature in features: - feature_reasons = decide_reasons.copy() - experiment_decision_found = False # Track if an experiment decision was made for the feature - - # Check if the feature flag is under an experiment - if feature.experimentIds: - for experiment_id in feature.experimentIds: - experiment = project_config.get_experiment_from_id(experiment_id) - decision_variation: Optional[Union[entities.Variation, VariationDict]] = None - - if experiment: - optimizely_decision_context = OptimizelyUserContext.OptimizelyDecisionContext( - feature.key, experiment.key) - forced_decision_variation, reasons_received = self.validated_forced_decision( - project_config, optimizely_decision_context, user_context) - feature_reasons.extend(reasons_received) - - if forced_decision_variation: - decision_variation = forced_decision_variation - cmab_uuid = None - error = False - else: - variation_result = self.get_variation( - project_config, experiment, user_context, user_profile_tracker, feature_reasons, options - ) - cmab_uuid = variation_result['cmab_uuid'] - variation_reasons = variation_result['reasons'] - decision_variation = variation_result['variation'] - error = variation_result['error'] - feature_reasons.extend(variation_reasons) - - if error: - decision = Decision(experiment, None, enums.DecisionSources.FEATURE_TEST, cmab_uuid) - decision_result: DecisionResult = { - 'decision': decision, - 'error': True, - 'reasons': feature_reasons - } - decisions.append(decision_result) - experiment_decision_found = True - break - - if decision_variation: - self.logger.debug( - f'User "{user_context.user_id}" ' - f'bucketed into experiment "{experiment.key}" of feature "{feature.key}".' - ) - decision = Decision(experiment, decision_variation, - enums.DecisionSources.FEATURE_TEST, cmab_uuid) - decision_result = { - 'decision': decision, - 'error': False, - 'reasons': feature_reasons - } - decisions.append(decision_result) - experiment_decision_found = True # Mark that a decision was found - break # Stop after the first successful experiment decision - - # Only process rollout if no experiment decision was found and no error - if not experiment_decision_found: - rollout_decision, rollout_reasons = self.get_variation_for_rollout(project_config, - feature, - user_context) - if rollout_reasons: - feature_reasons.extend(rollout_reasons) - if rollout_decision: - self.logger.debug(f'User "{user_context.user_id}" ' - f'bucketed into rollout for feature "{feature.key}".') - else: - self.logger.debug(f'User "{user_context.user_id}" ' - f'not bucketed into any rollout for feature "{feature.key}".') - - decision_result = { - 'decision': rollout_decision, - 'error': False, - 'reasons': feature_reasons - } - decisions.append(decision_result) + flag_decision_result = self.get_decision_for_flag( + feature_flag=feature, + user_context=user_context, + project_config=project_config, + decide_options=options, + user_profile_tracker=user_profile_tracker, + decide_reasons=None + ) + decisions.append(flag_decision_result) - if self.user_profile_service is not None and user_profile_tracker is not None and ignore_ups is False: + # Save user profile once after all features processed + if self.user_profile_service is not None and user_profile_tracker is not None and not ignore_ups: user_profile_tracker.save_user_profile() return decisions diff --git a/optimizely/entities.py b/optimizely/entities.py index 83488bdf6..12f4f8495 100644 --- a/optimizely/entities.py +++ b/optimizely/entities.py @@ -27,6 +27,8 @@ class BaseEntity: def __eq__(self, other: object) -> bool: + if not hasattr(other, '__dict__'): + return False return self.__dict__ == other.__dict__ @@ -194,3 +196,76 @@ def __init__(self, key: str, host: Optional[str] = None, publicKey: Optional[str self.key = key self.host = host self.publicKey = publicKey + + +class Holdout(BaseEntity): + """Holdout entity representing a holdout experiment for measuring incremental impact. + + Aligned with Swift SDK implementation where Holdout is a proper entity class + that conforms to ExperimentCore protocol. + """ + + class Status: + """Holdout status constants matching Swift enum Status.""" + DRAFT: Final = 'Draft' + RUNNING: Final = 'Running' + CONCLUDED: Final = 'Concluded' + ARCHIVED: Final = 'Archived' + + def __init__( + self, + id: str, + key: str, + status: str, + variations: list[VariationDict], + trafficAllocation: list[TrafficAllocation], + audienceIds: list[str], + includedFlags: Optional[list[str]] = None, + excludedFlags: Optional[list[str]] = None, + audienceConditions: Optional[Sequence[str | list[str]]] = None, + **kwargs: Any + ): + self.id = id + self.key = key + self.status = status + self.variations = variations + self.trafficAllocation = trafficAllocation + self.audienceIds = audienceIds + self.audienceConditions = audienceConditions + self.includedFlags = includedFlags or [] + self.excludedFlags = excludedFlags or [] + + def get_audience_conditions_or_ids(self) -> Sequence[str | list[str]]: + """Returns audienceConditions if present, otherwise audienceIds. + + This matches the Experiment.get_audience_conditions_or_ids() method + and enables holdouts to work with the same audience evaluation logic. + """ + return self.audienceConditions if self.audienceConditions is not None else self.audienceIds + + @property + def is_activated(self) -> bool: + """Check if the holdout is activated (running). + + Matches Swift's isActivated computed property: + var isActivated: Bool { return status == .running } + + Returns: + True if status is 'Running', False otherwise. + """ + return self.status == self.Status.RUNNING + + def __str__(self) -> str: + return self.key + + def __getitem__(self, key: str) -> Any: + """Enable dict-style access for backward compatibility with tests.""" + return getattr(self, key) + + def __setitem__(self, key: str, value: Any) -> None: + """Enable dict-style assignment for backward compatibility with tests.""" + setattr(self, key, value) + + def get(self, key: str, default: Any = None) -> Any: + """Enable dict-style .get() method for backward compatibility with tests.""" + return getattr(self, key, default) diff --git a/optimizely/event/event_factory.py b/optimizely/event/event_factory.py index 48b3a5ccf..f66c1d595 100644 --- a/optimizely/event/event_factory.py +++ b/optimizely/event/event_factory.py @@ -125,10 +125,14 @@ def _create_visitor(cls, event: Optional[user_event.UserEvent], logger: Logger) if isinstance(event.variation, entities.Variation): variation_id = event.variation.id variation_key = event.variation.key + elif isinstance(event.variation, dict): + variation_id = event.variation.get('id', '') + variation_key = event.variation.get('key', '') if event.experiment: - experiment_layerId = event.experiment.layerId experiment_id = event.experiment.id + if isinstance(event.experiment, entities.Experiment): + experiment_layerId = event.experiment.layerId metadata = payload.Metadata(event.flag_key, event.rule_key, event.rule_type, variation_key, diff --git a/optimizely/event/user_event.py b/optimizely/event/user_event.py index c1152161d..8006c052e 100644 --- a/optimizely/event/user_event.py +++ b/optimizely/event/user_event.py @@ -27,9 +27,10 @@ if TYPE_CHECKING: # prevent circular dependenacy by skipping import at runtime - from optimizely.entities import Experiment, Variation, Event + from optimizely.entities import Experiment, Variation, Event, Holdout from optimizely.event.payload import VisitorAttribute from optimizely.helpers.event_tag_utils import EventTags + from optimizely.helpers.types import VariationDict CLIENT_NAME: Final = 'python-sdk' @@ -63,9 +64,9 @@ def __init__( self, event_context: EventContext, user_id: str, - experiment: Experiment, + experiment: Experiment | Holdout, visitor_attributes: list[VisitorAttribute], - variation: Optional[Variation], + variation: Optional[Variation | VariationDict], flag_key: str, rule_key: str, rule_type: str, diff --git a/optimizely/event/user_event_factory.py b/optimizely/event/user_event_factory.py index 7a77720f0..a213a2780 100644 --- a/optimizely/event/user_event_factory.py +++ b/optimizely/event/user_event_factory.py @@ -23,7 +23,8 @@ # prevent circular dependenacy by skipping import at runtime from optimizely.optimizely_user_context import UserAttributes from optimizely.project_config import ProjectConfig - from optimizely.entities import Experiment, Variation + from optimizely.entities import Experiment, Variation, Holdout + from optimizely.helpers.types import VariationDict class UserEventFactory: @@ -33,7 +34,7 @@ class UserEventFactory: def create_impression_event( cls, project_config: ProjectConfig, - activated_experiment: Experiment, + activated_experiment: Experiment | Holdout, variation_id: Optional[str], flag_key: str, rule_key: str, @@ -64,16 +65,16 @@ def create_impression_event( if not activated_experiment and rule_type is not enums.DecisionSources.ROLLOUT: return None - variation: Optional[Variation] = None + variation: Optional[Variation | VariationDict] = None experiment_id = None if activated_experiment: experiment_id = activated_experiment.id - if variation_id and flag_key: + if variation_id and flag_key and rule_type != enums.DecisionSources.HOLDOUT: # need this condition when we send events involving forced decisions - # (F-to-D or E-to-D with any ruleKey/variationKey combinations) variation = project_config.get_flag_variation(flag_key, 'id', variation_id) elif variation_id and experiment_id: + # For holdouts, experiments, and rollouts - lookup by experiment/holdout ID variation = project_config.get_variation_from_id_by_experiment_id(experiment_id, variation_id) event_context = user_event.EventContext( diff --git a/optimizely/optimizely.py b/optimizely/optimizely.py index 7b27d8494..4b014e7f2 100644 --- a/optimizely/optimizely.py +++ b/optimizely/optimizely.py @@ -329,7 +329,8 @@ def _validate_user_inputs( return True def _send_impression_event( - self, project_config: project_config.ProjectConfig, experiment: Optional[entities.Experiment], + self, project_config: project_config.ProjectConfig, + experiment: Optional[Union[entities.Experiment, entities.Holdout]], variation: Optional[Union[entities.Variation, VariationDict]], flag_key: str, rule_key: str, rule_type: str, enabled: bool, user_id: str, attributes: Optional[UserAttributes], cmab_uuid: Optional[str] = None ) -> None: @@ -625,7 +626,8 @@ def activate(self, experiment_key: str, user_id: str, attributes: Optional[UserA self._send_impression_event(project_config, experiment, variation, '', experiment.key, enums.DecisionSources.EXPERIMENT, True, user_id, attributes) - return variation.key + # Handle both Variation entity and VariationDict + return variation['key'] if isinstance(variation, dict) else variation.key def track( self, event_key: str, user_id: str, @@ -1120,7 +1122,10 @@ def get_forced_variation(self, experiment_key: str, user_id: str) -> Optional[st return None forced_variation, _ = self.decision_service.get_forced_variation(project_config, experiment_key, user_id) - return forced_variation.key if forced_variation else None + if forced_variation: + # Handle both Variation entity and VariationDict + return forced_variation['key'] if isinstance(forced_variation, dict) else forced_variation.key + return None def get_optimizely_config(self) -> Optional[OptimizelyConfig]: """ Gets OptimizelyConfig instance for the current project config. @@ -1260,9 +1265,10 @@ def _create_optimizely_decision( feature_flag = project_config.feature_key_map.get(flag_key) # Send impression event if Decision came from a feature - # test and decide options doesn't include disableDecisionEvent if OptimizelyDecideOption.DISABLE_DECISION_EVENT not in decide_options: - if decision_source == DecisionSources.FEATURE_TEST or project_config.send_flag_decisions: + if (decision_source == DecisionSources.FEATURE_TEST or + decision_source == DecisionSources.HOLDOUT or + project_config.send_flag_decisions): self._send_impression_event(project_config, flag_decision.experiment, flag_decision.variation, diff --git a/optimizely/project_config.py b/optimizely/project_config.py index 23508bb67..74442d7ac 100644 --- a/optimizely/project_config.py +++ b/optimizely/project_config.py @@ -21,8 +21,6 @@ from .helpers import enums from .helpers import types -from optimizely.helpers.types import HoldoutDict, VariationDict - if version_info < (3, 8): from typing_extensions import Final else: @@ -31,6 +29,7 @@ if TYPE_CHECKING: # prevent circular dependenacy by skipping import at runtime from .logger import Logger + from .helpers.types import VariationDict SUPPORTED_VERSIONS = [ @@ -90,34 +89,44 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): region_value = config.get('region') self.region: str = region_value or 'US' - self.holdouts: list[HoldoutDict] = config.get('holdouts', []) - self.holdout_id_map: dict[str, HoldoutDict] = {} - self.global_holdouts: dict[str, HoldoutDict] = {} - self.included_holdouts: dict[str, list[HoldoutDict]] = {} - self.excluded_holdouts: dict[str, list[HoldoutDict]] = {} - self.flag_holdouts_map: dict[str, list[HoldoutDict]] = {} - - for holdout in self.holdouts: - if holdout.get('status') != 'Running': + # Parse holdouts from datafile and convert to Holdout entities + holdouts_data: list[types.HoldoutDict] = config.get('holdouts', []) + self.holdouts: list[entities.Holdout] = [] + self.holdout_id_map: dict[str, entities.Holdout] = {} + self.global_holdouts: list[entities.Holdout] = [] + self.included_holdouts: dict[str, list[entities.Holdout]] = {} + self.excluded_holdouts: dict[str, list[entities.Holdout]] = {} + self.flag_holdouts_map: dict[str, list[entities.Holdout]] = {} + + # Convert holdout dicts to Holdout entities + for holdout_data in holdouts_data: + # Create Holdout entity + holdout = entities.Holdout(**holdout_data) + self.holdouts.append(holdout) + + # Only process Running holdouts but doing it here for efficiency like the original Python implementation) + if not holdout.is_activated: continue - holdout_id = holdout['id'] - self.holdout_id_map[holdout_id] = holdout + # Map by ID for quick lookup + self.holdout_id_map[holdout.id] = holdout - included_flags = holdout.get('includedFlags') - if not included_flags: + # Categorize as global vs flag-specific + # Global holdouts: apply to all flags unless explicitly excluded + # Flag-specific holdouts: only apply to explicitly included flags + if not holdout.includedFlags: # This is a global holdout - self.global_holdouts[holdout_id] = holdout + self.global_holdouts.append(holdout) - excluded_flags = holdout.get('excludedFlags') - if excluded_flags: - for flag_id in excluded_flags: + # Track which flags this global holdout excludes + if holdout.excludedFlags: + for flag_id in holdout.excludedFlags: if flag_id not in self.excluded_holdouts: self.excluded_holdouts[flag_id] = [] self.excluded_holdouts[flag_id].append(holdout) else: - # This holdout applies to specific flags - for flag_id in included_flags: + # This holdout applies to specific flags only + for flag_id in holdout.includedFlags: if flag_id not in self.included_holdouts: self.included_holdouts[flag_id] = [] self.included_holdouts[flag_id].append(holdout) @@ -173,11 +182,11 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): self.all_segments += audience.get_segments() self.experiment_key_map: dict[str, entities.Experiment] = {} - self.variation_key_map: dict[str, dict[str, entities.Variation]] = {} - self.variation_id_map: dict[str, dict[str, entities.Variation]] = {} + self.variation_key_map: dict[str, dict[str, Union[entities.Variation, VariationDict]]] = {} + self.variation_id_map: dict[str, dict[str, Union[entities.Variation, VariationDict]]] = {} self.variation_variable_usage_map: dict[str, dict[str, entities.Variation.VariableUsage]] = {} - self.variation_id_map_by_experiment_id: dict[str, dict[str, entities.Variation]] = {} - self.variation_key_map_by_experiment_id: dict[str, dict[str, entities.Variation]] = {} + self.variation_id_map_by_experiment_id: dict[str, dict[str, Union[entities.Variation, VariationDict]]] = {} + self.variation_key_map_by_experiment_id: dict[str, dict[str, Union[entities.Variation, VariationDict]]] = {} self.flag_variations_map: dict[str, list[entities.Variation]] = {} for experiment in self.experiment_id_map.values(): @@ -191,11 +200,13 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): self.variation_key_map_by_experiment_id[experiment.id] = {} for variation in self.variation_key_map[experiment.key].values(): - self.variation_id_map[experiment.key][variation.id] = variation - self.variation_id_map_by_experiment_id[experiment.id][variation.id] = variation - self.variation_key_map_by_experiment_id[experiment.id][variation.key] = variation - self.variation_variable_usage_map[variation.id] = self._generate_key_map( - variation.variables, 'id', entities.Variation.VariableUsage + # Cast is safe here because experiments always use Variation entities, not VariationDict + var = cast(entities.Variation, variation) + self.variation_id_map[experiment.key][var.id] = var + self.variation_id_map_by_experiment_id[experiment.id][var.id] = var + self.variation_key_map_by_experiment_id[experiment.id][var.key] = var + self.variation_variable_usage_map[var.id] = self._generate_key_map( + var.variables, 'id', entities.Variation.VariableUsage ) self.feature_key_map = self._generate_key_map(self.feature_flags, 'key', entities.FeatureFlag) @@ -222,16 +233,18 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): rules.append(self.experiment_id_map[exp_id]) flag_id = feature.id - applicable_holdouts = [] + applicable_holdouts: list[entities.Holdout] = [] + + # Add global holdouts first, excluding any that are explicitly excluded for this flag + excluded_holdouts = self.excluded_holdouts.get(flag_id, []) + for holdout in self.global_holdouts: + if holdout not in excluded_holdouts: + applicable_holdouts.append(holdout) + # Add flag-specific local holdouts AFTER global holdouts if flag_id in self.included_holdouts: applicable_holdouts.extend(self.included_holdouts[flag_id]) - for holdout in self.global_holdouts.values(): - excluded_flag_ids = holdout.get('excludedFlags', []) - if flag_id not in excluded_flag_ids: - applicable_holdouts.append(holdout) - if applicable_holdouts: self.flag_holdouts_map[feature.key] = applicable_holdouts @@ -244,33 +257,28 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): # variation_id_map_by_experiment_id gives variation entity object while # experiment_id_map will give us dictionary for rule_variation in self.variation_id_map_by_experiment_id[rule.id].values(): - if len(list(filter(lambda variation: variation.id == rule_variation.id, variations))) == 0: - variations.append(rule_variation) + # Cast is safe here because rollout rules use Variation entities + rule_var = cast(entities.Variation, rule_variation) + if len(list(filter(lambda variation: variation.id == rule_var.id, variations))) == 0: + variations.append(rule_var) self.flag_variations_map[feature.key] = variations + # Process holdout variations are converted to Variation entities just like experiment variations if self.holdouts: for holdout in self.holdouts: - holdout_key = holdout.get('key') - holdout_id = holdout.get('id') - - if not holdout_key or not holdout_id: - continue - - self.variation_key_map[holdout_key] = {} - self.variation_id_map[holdout_key] = {} - self.variation_id_map_by_experiment_id[holdout_id] = {} - self.variation_key_map_by_experiment_id[holdout_id] = {} - - variations = holdout.get('variations') - if variations: - for variation in variations: - variation_key = variation.get('key') if isinstance(variation, dict) else None - variation_id = variation.get('id') if isinstance(variation, dict) else None - if variation_key and variation_id: - self.variation_key_map[holdout_key][variation_key] = variation - self.variation_id_map[holdout_key][variation_id] = variation - self.variation_key_map_by_experiment_id[holdout_id][variation_key] = variation - self.variation_id_map_by_experiment_id[holdout_id][variation_id] = variation + # Initialize variation maps for this holdout + self.variation_key_map[holdout.key] = {} + self.variation_id_map[holdout.key] = {} + self.variation_id_map_by_experiment_id[holdout.id] = {} + self.variation_key_map_by_experiment_id[holdout.id] = {} + + if holdout.variations: + for variation_dict in holdout.variations: + # Map variations by key and ID using dict format + self.variation_key_map[holdout.key][variation_dict['key']] = variation_dict + self.variation_id_map[holdout.key][variation_dict['id']] = variation_dict + self.variation_key_map_by_experiment_id[holdout.id][variation_dict['key']] = variation_dict + self.variation_id_map_by_experiment_id[holdout.id][variation_dict['id']] = variation_dict @staticmethod def _generate_key_map( @@ -488,7 +496,9 @@ def get_audience(self, audience_id: str) -> Optional[entities.Audience]: self.error_handler.handle_error(exceptions.InvalidAudienceException((enums.Errors.INVALID_AUDIENCE))) return None - def get_variation_from_key(self, experiment_key: str, variation_key: str) -> Optional[entities.Variation]: + def get_variation_from_key( + self, experiment_key: str, variation_key: str + ) -> Optional[Union[entities.Variation, VariationDict]]: """ Get variation given experiment and variation key. Args: @@ -515,7 +525,9 @@ def get_variation_from_key(self, experiment_key: str, variation_key: str) -> Opt self.error_handler.handle_error(exceptions.InvalidExperimentException(enums.Errors.INVALID_EXPERIMENT_KEY)) return None - def get_variation_from_id(self, experiment_key: str, variation_id: str) -> Optional[entities.Variation]: + def get_variation_from_id( + self, experiment_key: str, variation_id: str + ) -> Optional[Union[entities.Variation, VariationDict]]: """ Get variation given experiment and variation ID. Args: @@ -761,7 +773,7 @@ def is_feature_experiment(self, experiment_id: str) -> bool: def get_variation_from_id_by_experiment_id( self, experiment_id: str, variation_id: str - ) -> Optional[entities.Variation]: + ) -> Optional[Union[entities.Variation, VariationDict]]: """ Gets variation from variation id and specific experiment id Returns: @@ -780,7 +792,7 @@ def get_variation_from_id_by_experiment_id( def get_variation_from_key_by_experiment_id( self, experiment_id: str, variation_key: str - ) -> Optional[entities.Variation]: + ) -> Optional[Union[entities.Variation, VariationDict]]: """ Gets variation from variation key and specific experiment id Returns: @@ -834,28 +846,28 @@ def get_flag_variation( return None - def get_holdouts_for_flag(self, flag_key: str) -> list[HoldoutDict]: + def get_holdouts_for_flag(self, flag_key: str) -> list[entities.Holdout]: """ Helper method to get holdouts from an applied feature flag. Args: flag_key: Key of the feature flag. Returns: - The holdouts that apply for a specific flag. + The holdouts that apply for a specific flag as Holdout entity objects. """ if not self.holdouts: return [] return self.flag_holdouts_map.get(flag_key, []) - def get_holdout(self, holdout_id: str) -> Optional[HoldoutDict]: + def get_holdout(self, holdout_id: str) -> Optional[entities.Holdout]: """ Helper method to get holdout from holdout ID. Args: holdout_id: ID of the holdout. Returns: - The holdout corresponding to the provided holdout ID. + The holdout corresponding to the provided holdout ID as a Holdout entity object. """ holdout = self.holdout_id_map.get(holdout_id) diff --git a/tests/test_config.py b/tests/test_config.py index 08a81f6d8..81228febf 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1393,6 +1393,9 @@ def setUp(self): 'id': 'holdout_1', 'key': 'global_holdout', 'status': 'Running', + 'variations': [], + 'trafficAllocation': [], + 'audienceIds': [], 'includedFlags': [], 'excludedFlags': [boolean_feature_id] }, @@ -1400,6 +1403,9 @@ def setUp(self): 'id': 'holdout_2', 'key': 'specific_holdout', 'status': 'Running', + 'variations': [], + 'trafficAllocation': [], + 'audienceIds': [], 'includedFlags': [multi_variate_feature_id], 'excludedFlags': [] }, @@ -1407,6 +1413,9 @@ def setUp(self): 'id': 'holdout_3', 'key': 'inactive_holdout', 'status': 'Inactive', + 'variations': [], + 'trafficAllocation': [], + 'audienceIds': [], 'includedFlags': [boolean_feature_id], 'excludedFlags': [] } @@ -1512,7 +1521,9 @@ def test_holdout_initialization__categorizes_holdouts_properly(self): self.assertIn('holdout_1', self.config_with_holdouts.holdout_id_map) self.assertIn('holdout_2', self.config_with_holdouts.holdout_id_map) - self.assertIn('holdout_1', self.config_with_holdouts.global_holdouts) + # Check if a holdout with ID 'holdout_1' exists in global_holdouts + holdout_ids_in_global = [h.id for h in self.config_with_holdouts.global_holdouts] + self.assertIn('holdout_1', holdout_ids_in_global) # Use correct feature flag IDs boolean_feature_id = '91111' diff --git a/tests/test_decision_service_holdout.py b/tests/test_decision_service_holdout.py index 0f47e9975..e286ba5ca 100644 --- a/tests/test_decision_service_holdout.py +++ b/tests/test_decision_service_holdout.py @@ -147,8 +147,8 @@ def test_holdout_inactive_does_not_bucket_users(self): self.assertIsNotNone(holdout) # Mock holdout as inactive - original_status = holdout['status'] - holdout['status'] = 'Paused' + original_status = holdout.status + holdout.status = 'Paused' user_context = self.opt_obj.create_user_context('testUserId', {}) @@ -164,7 +164,7 @@ def test_holdout_inactive_does_not_bucket_users(self): self.assertIn('reasons', result) # Restore original status - holdout['status'] = original_status + holdout.status = original_status def test_user_not_bucketed_into_holdout_executes_successfully(self): """When user is not bucketed into holdout, should execute successfully with valid result structure.""" @@ -282,7 +282,7 @@ def test_user_bucketed_into_holdout_returns_before_experiments(self): holdout = self.config_with_holdouts.holdouts[0] if self.config_with_holdouts.holdouts else None self.assertIsNotNone(holdout) - holdout_variation = holdout['variations'][0] + holdout_variation = holdout.variations[0] # Create a holdout decision mock_holdout_decision = decision_service.Decision( @@ -384,7 +384,7 @@ def test_evaluates_global_holdouts_for_all_flags(self): # Get global holdouts global_holdouts = [ h for h in self.config_with_holdouts.holdouts - if not h.get('includedFlags') or len(h.get('includedFlags', [])) == 0 + if not h.includedFlags or len(h.includedFlags) == 0 ] if global_holdouts: @@ -409,7 +409,7 @@ def test_respects_included_and_excluded_flags_configuration(self): holdouts_for_flag = self.config_with_holdouts.get_holdouts_for_flag('test_feature_in_experiment') # Should not include holdouts that exclude this flag - excluded_holdout = next((h for h in holdouts_for_flag if h.get('key') == 'excluded_holdout'), None) + excluded_holdout = next((h for h in holdouts_for_flag if h.key == 'excluded_holdout'), None) self.assertIsNone(excluded_holdout) # Holdout logging and error handling tests @@ -507,9 +507,18 @@ def test_uses_consistent_bucketing_for_same_user(self): # If both have decisions, they should match if decision1 and decision2: - # Variation is an object, not a dict, so use attributes - var1_id = decision1.variation.id if decision1.variation else None - var2_id = decision2.variation.id if decision2.variation else None + # Handle both dict and Variation entity formats + if decision1.variation: + var1_id = (decision1.variation['id'] if isinstance(decision1.variation, dict) + else decision1.variation.id) + else: + var1_id = None + + if decision2.variation: + var2_id = (decision2.variation['id'] if isinstance(decision2.variation, dict) + else decision2.variation.id) + else: + var2_id = None self.assertEqual( var1_id, var2_id, @@ -666,7 +675,7 @@ def test_decide_with_holdout_sends_impression_event(self): actual_holdout = None if config.holdouts and decision.rule_key: actual_holdout = next( - (h for h in config.holdouts if h.get('key') == decision.rule_key), + (h for h in config.holdouts if h.key == decision.rule_key), None ) @@ -675,13 +684,13 @@ def test_decide_with_holdout_sends_impression_event(self): self.assertEqual(decision.flag_key, feature_flag.key) holdout_variation = next( - (v for v in actual_holdout['variations'] if v.get('key') == decision.variation_key), + (v for v in actual_holdout.variations if v.get('key') == decision.variation_key), None ) self.assertIsNotNone( holdout_variation, - f"Variation '{decision.variation_key}' should be from the chosen holdout '{actual_holdout['key']}'" + f"Variation '{decision.variation_key}' should be from the chosen holdout '{actual_holdout.key}'" ) self.assertEqual( @@ -767,7 +776,7 @@ def test_decide_with_holdout_does_not_send_impression_when_disabled(self): chosen_holdout = None if config.holdouts and decision.rule_key: chosen_holdout = next( - (h for h in config.holdouts if h.get('key') == decision.rule_key), + (h for h in config.holdouts if h.key == decision.rule_key), None ) @@ -831,12 +840,12 @@ def notification_callback(notification_type, user_id, user_attributes, decision_ holdout = config.holdouts[0] if config.holdouts else None self.assertIsNotNone(holdout, 'Should have at least one holdout configured') - holdout_variation = holdout['variations'][0] + holdout_variation = holdout.variations[0] self.assertIsNotNone(holdout_variation, 'Holdout should have at least one variation') mock_experiment = mock.MagicMock() - mock_experiment.key = holdout['key'] - mock_experiment.id = holdout['id'] + mock_experiment.key = holdout.key + mock_experiment.id = holdout.id # Mock the decision service to return a holdout decision holdout_decision = decision_service.Decision( @@ -867,7 +876,7 @@ def notification_callback(notification_type, user_id, user_attributes, decision_ notification = captured_notifications[0] rule_key = notification.get('rule_key') - self.assertEqual(rule_key, holdout['key'], 'RuleKey should match holdout key') + self.assertEqual(rule_key, holdout.key, 'RuleKey should match holdout key') # Verify holdout notification structure self.assertIn('flag_key', notification, 'Holdout notification should contain flag_key') @@ -880,7 +889,7 @@ def notification_callback(notification_type, user_id, user_attributes, decision_ self.assertEqual(flag_key, 'test_feature_in_experiment', 'FlagKey should match the requested flag') experiment_id = notification.get('experiment_id') - self.assertEqual(experiment_id, holdout['id'], 'ExperimentId in notification should match holdout ID') + self.assertEqual(experiment_id, holdout.id, 'ExperimentId in notification should match holdout ID') variation_id = notification.get('variation_id') self.assertEqual(variation_id, holdout_variation['id'], 'VariationId should match holdout variation ID') @@ -910,3 +919,552 @@ def notification_callback(notification_type, user_id, user_attributes, decision_ ) finally: opt_with_mocked_events.close() + + # DecideAll with holdouts tests (aligned with Swift SDK) + + def test_decide_all_with_global_holdout(self): + """Should apply global holdout to all flags in decide_all.""" + config_dict_with_holdouts = self.config_dict_with_features.copy() + config_dict_with_holdouts['holdouts'] = [ + { + 'id': 'global_holdout', + 'key': 'global_test_holdout', + 'status': 'Running', + 'includedFlags': [], # Global - applies to all flags + 'excludedFlags': [], + 'audienceIds': [], + 'variations': [ + { + 'id': 'global_holdout_var', + 'key': 'global_holdout_control', + 'featureEnabled': False, + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'global_holdout_var', + 'endOfRange': 10000 + } + ] + } + ] + + config_json = json.dumps(config_dict_with_holdouts) + opt = optimizely_module.Optimizely(datafile=config_json) + + try: + user_context = opt.create_user_context('test_user', {}) + decisions = user_context.decide_all() + + # Global holdout should apply to all flags + self.assertGreater(len(decisions), 0) + + # Check that decisions exist for all flags + for flag_key, decision in decisions.items(): + self.assertIsNotNone(decision) + finally: + opt.close() + + def test_decide_all_with_included_flags(self): + """Should apply holdout only to included flags in decide_all.""" + # Get feature flag IDs + feature1_id = '91111' # test_feature_in_experiment + + config_dict_with_holdouts = self.config_dict_with_features.copy() + config_dict_with_holdouts['holdouts'] = [ + { + 'id': 'included_holdout', + 'key': 'specific_holdout', + 'status': 'Running', + 'includedFlags': [feature1_id], # Only applies to feature1 + 'excludedFlags': [], + 'audienceIds': [], + 'variations': [ + { + 'id': 'included_var', + 'key': 'included_control', + 'featureEnabled': False, + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'included_var', + 'endOfRange': 10000 + } + ] + } + ] + + config_json = json.dumps(config_dict_with_holdouts) + opt = optimizely_module.Optimizely(datafile=config_json) + + try: + user_context = opt.create_user_context('test_user', {}) + decisions = user_context.decide_all() + + self.assertGreater(len(decisions), 0) + + # Verify all flags have decisions + for decision in decisions.values(): + self.assertIsNotNone(decision) + finally: + opt.close() + + def test_decide_all_with_excluded_flags(self): + """Should exclude holdout from excluded flags in decide_all.""" + feature1_id = '91111' # test_feature_in_experiment + + config_dict_with_holdouts = self.config_dict_with_features.copy() + config_dict_with_holdouts['holdouts'] = [ + { + 'id': 'excluded_holdout', + 'key': 'global_except_one', + 'status': 'Running', + 'includedFlags': [], # Global + 'excludedFlags': [feature1_id], # Except feature1 + 'audienceIds': [], + 'variations': [ + { + 'id': 'excluded_var', + 'key': 'excluded_control', + 'featureEnabled': False, + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'excluded_var', + 'endOfRange': 10000 + } + ] + } + ] + + config_json = json.dumps(config_dict_with_holdouts) + opt = optimizely_module.Optimizely(datafile=config_json) + + try: + user_context = opt.create_user_context('test_user', {}) + decisions = user_context.decide_all() + + # Verify decisions exist for all flags + self.assertGreater(len(decisions), 0) + for decision in decisions.values(): + self.assertIsNotNone(decision) + finally: + opt.close() + + def test_decide_all_with_multiple_holdouts(self): + """Should handle multiple holdouts with correct priority.""" + feature1_id = '91111' + feature2_id = '91112' + + config_dict_with_holdouts = self.config_dict_with_features.copy() + config_dict_with_holdouts['holdouts'] = [ + # Global holdout (applies to all) + { + 'id': 'global_holdout', + 'key': 'global_holdout', + 'status': 'Running', + 'includedFlags': [], + 'excludedFlags': [], + 'audienceIds': [], + 'variations': [ + { + 'id': 'global_var', + 'key': 'global_control', + 'featureEnabled': False, + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'global_var', + 'endOfRange': 10000 + } + ] + }, + # Specific holdout (only for feature2) + { + 'id': 'specific_holdout', + 'key': 'specific_holdout', + 'status': 'Running', + 'includedFlags': [feature2_id], + 'excludedFlags': [], + 'audienceIds': [], + 'variations': [ + { + 'id': 'specific_var', + 'key': 'specific_control', + 'featureEnabled': False, + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'specific_var', + 'endOfRange': 10000 + } + ] + }, + # Excluded holdout (all except feature1) + { + 'id': 'excluded_holdout', + 'key': 'excluded_holdout', + 'status': 'Running', + 'includedFlags': [], + 'excludedFlags': [feature1_id], + 'audienceIds': [], + 'variations': [ + { + 'id': 'excluded_var', + 'key': 'excluded_control', + 'featureEnabled': False, + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'excluded_var', + 'endOfRange': 10000 + } + ] + } + ] + + config_json = json.dumps(config_dict_with_holdouts) + opt = optimizely_module.Optimizely(datafile=config_json) + + try: + user_context = opt.create_user_context('test_user', {}) + decisions = user_context.decide_all() + + # Verify we got decisions for all flags + self.assertGreater(len(decisions), 0) + finally: + opt.close() + + def test_decide_all_with_enabled_flags_only_option(self): + """Should filter out disabled flags when using enabled_flags_only option.""" + config_dict_with_holdouts = self.config_dict_with_features.copy() + config_dict_with_holdouts['holdouts'] = [ + { + 'id': 'disabled_holdout', + 'key': 'disabled_holdout', + 'status': 'Running', + 'includedFlags': [], + 'excludedFlags': [], + 'audienceIds': [], + 'variations': [ + { + 'id': 'disabled_var', + 'key': 'disabled_control', + 'featureEnabled': False, # Feature disabled + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'disabled_var', + 'endOfRange': 10000 + } + ] + } + ] + + config_json = json.dumps(config_dict_with_holdouts) + opt = optimizely_module.Optimizely(datafile=config_json) + + try: + user_context = opt.create_user_context('test_user', {}) + + # Without enabled_flags_only, all flags should be returned + all_decisions = user_context.decide_all() + + # With enabled_flags_only, disabled flags should be filtered out + enabled_decisions = user_context.decide_all( + options=[OptimizelyDecideOption.ENABLED_FLAGS_ONLY] + ) + + # enabled_decisions should have fewer or equal entries + self.assertLessEqual(len(enabled_decisions), len(all_decisions)) + finally: + opt.close() + + # Impression event metadata tests (aligned with Swift SDK) + + def test_holdout_impression_event_has_correct_metadata(self): + """Should include correct metadata in holdout impression events.""" + config_dict_with_holdouts = self.config_dict_with_features.copy() + config_dict_with_holdouts['holdouts'] = [ + { + 'id': 'metadata_holdout', + 'key': 'metadata_test_holdout', + 'status': 'Running', + 'includedFlags': [], + 'excludedFlags': [], + 'audienceIds': [], + 'variations': [ + { + 'id': 'metadata_var', + 'key': 'metadata_control', + 'featureEnabled': False, + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'metadata_var', + 'endOfRange': 10000 + } + ] + } + ] + + spy_event_processor = mock.MagicMock() + + config_json = json.dumps(config_dict_with_holdouts) + opt = optimizely_module.Optimizely( + datafile=config_json, + event_processor=spy_event_processor + ) + + try: + user_context = opt.create_user_context('test_user', {}) + decision = user_context.decide('test_feature_in_experiment') + + # If this was a holdout decision, verify event metadata + if decision.rule_key == 'metadata_test_holdout': + self.assertGreater(spy_event_processor.process.call_count, 0) + + # Get the user event that was sent + call_args = spy_event_processor.process.call_args_list[0] + user_event = call_args[0][0] + + # Verify user event has correct structure + self.assertIsNotNone(user_event) + finally: + opt.close() + + def test_holdout_impression_respects_send_flag_decisions_false(self): + """Should send holdout impression even when sendFlagDecisions is false.""" + config_dict_with_holdouts = self.config_dict_with_features.copy() + config_dict_with_holdouts['sendFlagDecisions'] = False + config_dict_with_holdouts['holdouts'] = [ + { + 'id': 'send_flag_holdout', + 'key': 'send_flag_test_holdout', + 'status': 'Running', + 'includedFlags': [], + 'excludedFlags': [], + 'audienceIds': [], + 'variations': [ + { + 'id': 'send_flag_var', + 'key': 'send_flag_control', + 'featureEnabled': False, + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'send_flag_var', + 'endOfRange': 10000 + } + ] + } + ] + + spy_event_processor = mock.MagicMock() + + config_json = json.dumps(config_dict_with_holdouts) + opt = optimizely_module.Optimizely( + datafile=config_json, + event_processor=spy_event_processor + ) + + try: + user_context = opt.create_user_context('test_user', {}) + decision = user_context.decide('test_feature_in_experiment') + + # Holdout impressions should be sent even when sendFlagDecisions=false + # (unlike rollout impressions) + if decision.rule_key == 'send_flag_test_holdout': + # Verify impression was sent for holdout + self.assertGreater(spy_event_processor.process.call_count, 0) + finally: + opt.close() + + # Holdout status tests (aligned with Swift SDK) + + def test_holdout_not_running_does_not_apply(self): + """Should not apply holdout when status is not Running.""" + config_dict_with_holdouts = self.config_dict_with_features.copy() + config_dict_with_holdouts['holdouts'] = [ + { + 'id': 'draft_holdout', + 'key': 'draft_holdout', + 'status': 'Draft', # Not Running + 'includedFlags': [], + 'excludedFlags': [], + 'audienceIds': [], + 'variations': [ + { + 'id': 'draft_var', + 'key': 'draft_control', + 'featureEnabled': False, + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'draft_var', + 'endOfRange': 10000 + } + ] + } + ] + + config_json = json.dumps(config_dict_with_holdouts) + opt = optimizely_module.Optimizely(datafile=config_json) + + try: + user_context = opt.create_user_context('test_user', {}) + decision = user_context.decide('test_feature_in_experiment') + + # Should not be a holdout decision since status is Draft + self.assertNotEqual(decision.rule_key, 'draft_holdout') + finally: + opt.close() + + def test_holdout_concluded_status_does_not_apply(self): + """Should not apply holdout when status is Concluded.""" + config_dict_with_holdouts = self.config_dict_with_features.copy() + config_dict_with_holdouts['holdouts'] = [ + { + 'id': 'concluded_holdout', + 'key': 'concluded_holdout', + 'status': 'Concluded', + 'includedFlags': [], + 'excludedFlags': [], + 'audienceIds': [], + 'variations': [ + { + 'id': 'concluded_var', + 'key': 'concluded_control', + 'featureEnabled': False, + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'concluded_var', + 'endOfRange': 10000 + } + ] + } + ] + + config_json = json.dumps(config_dict_with_holdouts) + opt = optimizely_module.Optimizely(datafile=config_json) + + try: + user_context = opt.create_user_context('test_user', {}) + decision = user_context.decide('test_feature_in_experiment') + + # Should not be a holdout decision since status is Concluded + self.assertNotEqual(decision.rule_key, 'concluded_holdout') + finally: + opt.close() + + def test_holdout_archived_status_does_not_apply(self): + """Should not apply holdout when status is Archived.""" + config_dict_with_holdouts = self.config_dict_with_features.copy() + config_dict_with_holdouts['holdouts'] = [ + { + 'id': 'archived_holdout', + 'key': 'archived_holdout', + 'status': 'Archived', + 'includedFlags': [], + 'excludedFlags': [], + 'audienceIds': [], + 'variations': [ + { + 'id': 'archived_var', + 'key': 'archived_control', + 'featureEnabled': False, + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'archived_var', + 'endOfRange': 10000 + } + ] + } + ] + + config_json = json.dumps(config_dict_with_holdouts) + opt = optimizely_module.Optimizely(datafile=config_json) + + try: + user_context = opt.create_user_context('test_user', {}) + decision = user_context.decide('test_feature_in_experiment') + + # Should not be a holdout decision since status is Archived + self.assertNotEqual(decision.rule_key, 'archived_holdout') + finally: + opt.close() + + # Audience targeting tests for holdouts (aligned with Swift SDK) + + def test_holdout_with_audience_match(self): + """Should bucket user into holdout when audience conditions match.""" + # Using audienceIds that exist in the datafile + # audience '11154' is for "browser_type" = "chrome" + config_dict_with_holdouts = self.config_dict_with_features.copy() + config_dict_with_holdouts['holdouts'] = [ + { + 'id': 'audience_holdout', + 'key': 'audience_test_holdout', + 'status': 'Running', + 'includedFlags': [], + 'excludedFlags': [], + 'audienceIds': ['11154'], # Requires browser_type=chrome + 'variations': [ + { + 'id': 'audience_var', + 'key': 'audience_control', + 'featureEnabled': False, + 'variables': [] + } + ], + 'trafficAllocation': [ + { + 'entityId': 'audience_var', + 'endOfRange': 10000 + } + ] + } + ] + + config_json = json.dumps(config_dict_with_holdouts) + opt = optimizely_module.Optimizely(datafile=config_json) + + try: + # User with matching attribute + user_context_match = opt.create_user_context('test_user', {'browser_type': 'chrome'}) + decision_match = user_context_match.decide('test_feature_in_experiment') + + # User with non-matching attribute + user_context_no_match = opt.create_user_context('test_user', {'browser_type': 'firefox'}) + decision_no_match = user_context_no_match.decide('test_feature_in_experiment') + + # Both should have valid decisions + self.assertIsNotNone(decision_match) + self.assertIsNotNone(decision_no_match) + finally: + opt.close() From f253379457863970f4da90751b4c33fd3aff4013 Mon Sep 17 00:00:00 2001 From: esrakartalOpt <102107327+esrakartalOpt@users.noreply.github.com> Date: Fri, 19 Dec 2025 10:28:33 -0600 Subject: [PATCH 09/32] [FSSDK-12094] chore: preparing for release v5.4.0 (#473) * [FSSDK-12094] chore: preparing for release v5.3.1 * Update changelog * Updated 5.3.0 version with holdout * Correct the version number * Correct the changelog with holdout features --- CHANGELOG.md | 19 +++++++++++++++++++ optimizely/version.py | 2 +- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 807fa2424..f5091a0e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Optimizely Python SDK Changelog +## 5.4.0 +December 19th, 2025 + +### New Features + +Holdout features: + +- Added support for Holdouts in Feature Experimentation, enabling global traffic exclusion from experiments for statistical confidence validation. ([#469](https://github.com/optimizely/python-sdk/pull/469)) +- Added holdout support for default decision service ([#467](https://github.com/optimizely/python-sdk/pull/467)) +- Project Config updated for Holdout ([#464](https://github.com/optimizely/python-sdk/pull/464)) + +--- + +### Bug Fixes +- Resolved issues with Holdout impression event handling and notification delivery. ([#471](https://github.com/optimizely/python-sdk/pull/471)) + +--- + + ## 5.3.0 November 13th, 2025 diff --git a/optimizely/version.py b/optimizely/version.py index eea99d940..aef5b3670 100644 --- a/optimizely/version.py +++ b/optimizely/version.py @@ -11,5 +11,5 @@ # See the License for the specific language governing permissions and # limitations under the License. -version_info = (5, 3, 0) +version_info = (5, 4, 0) __version__ = '.'.join(str(v) for v in version_info) From eadf141b00d21131ca0e214d10d351b6156b2c34 Mon Sep 17 00:00:00 2001 From: Farhan Anjum Date: Fri, 2 Jan 2026 22:04:18 +0600 Subject: [PATCH 10/32] [FSSDK-12035] Update: Exclude CMAB from UserProfileService (#474) * Python: Exclude CMAB experiments from user profile updates and add related tests * linting fix * chore: trigger tests * Python: Exclude CMAB experiments from user profile updates and update related tests * Python: Exclude CMAB experiments from user profile storage in decision service * Python: Remove test for CMAB experiments with IGNORE_USER_PROFILE_SERVICE option --- optimizely/decision_service.py | 5 ++ tests/test_decision_service.py | 118 +++++++++++++++++++++++++++++++++ 2 files changed, 123 insertions(+) diff --git a/optimizely/decision_service.py b/optimizely/decision_service.py index 28275ef65..be2be2c54 100644 --- a/optimizely/decision_service.py +++ b/optimizely/decision_service.py @@ -515,6 +515,11 @@ def get_variation( 'reasons': decide_reasons, 'variation': None } + ignore_user_profile = True + self.logger.debug( + f'Skipping user profile service for CMAB experiment "{experiment.key}". ' + f'CMAB decisions are dynamic and not stored for sticky bucketing.' + ) variation_id = cmab_decision['variation_id'] if cmab_decision else None cmab_uuid = cmab_decision['cmab_uuid'] if cmab_decision else None variation = project_config.get_variation_from_id(experiment_key=experiment.key, diff --git a/tests/test_decision_service.py b/tests/test_decision_service.py index dbcb74365..b38a03b20 100644 --- a/tests/test_decision_service.py +++ b/tests/test_decision_service.py @@ -1074,6 +1074,124 @@ def test_get_variation_cmab_experiment_with_whitelisted_variation(self): mock_bucket.assert_not_called() mock_cmab_decision.assert_not_called() + def test_get_variation_cmab_experiment_does_not_save_user_profile(self): + """Test that CMAB experiments do not save bucketing decisions to user profile.""" + + # Create a user context + user = optimizely_user_context.OptimizelyUserContext( + optimizely_client=None, + logger=None, + user_id="test_user", + user_attributes={} + ) + + # Create a user profile service and tracker + user_profile_service = user_profile.UserProfileService() + user_profile_tracker = user_profile.UserProfileTracker(user.user_id, user_profile_service) + + # Create a CMAB experiment + cmab_experiment = entities.Experiment( + '111150', + 'cmab_experiment', + 'Running', + '111150', + [], # No audience IDs + {}, + [ + entities.Variation('111151', 'variation_1'), + entities.Variation('111152', 'variation_2') + ], + [ + {'entityId': '111151', 'endOfRange': 5000}, + {'entityId': '111152', 'endOfRange': 10000} + ], + cmab={'trafficAllocation': 5000} + ) + + with mock.patch('optimizely.helpers.experiment.is_experiment_running', return_value=True), \ + mock.patch('optimizely.helpers.audience.does_user_meet_audience_conditions', return_value=[True, []]), \ + mock.patch.object(self.decision_service.bucketer, 'bucket_to_entity_id', + return_value=['$', []]), \ + mock.patch.object(self.decision_service, 'cmab_service') as mock_cmab_service, \ + mock.patch.object(self.project_config, 'get_variation_from_id', + return_value=entities.Variation('111151', 'variation_1')), \ + mock.patch.object(user_profile_tracker, 'update_user_profile') as mock_update_profile, \ + mock.patch.object(self.decision_service, 'logger') as mock_logger: + + # Configure CMAB service to return a decision + mock_cmab_service.get_decision.return_value = ( + { + 'variation_id': '111151', + 'cmab_uuid': 'test-cmab-uuid-123' + }, + [] # reasons list + ) + + # Call get_variation with the CMAB experiment and user profile tracker + variation_result = self.decision_service.get_variation( + self.project_config, + cmab_experiment, + user, + user_profile_tracker + ) + variation = variation_result['variation'] + cmab_uuid = variation_result['cmab_uuid'] + + # Verify the variation and cmab_uuid are returned + self.assertEqual(entities.Variation('111151', 'variation_1'), variation) + self.assertEqual('test-cmab-uuid-123', cmab_uuid) + + # Verify user profile was NOT updated for CMAB experiment + mock_update_profile.assert_not_called() + + # Verify debug log was called to explain CMAB exclusion + mock_logger.debug.assert_any_call( + 'Skipping user profile service for CMAB experiment "cmab_experiment". ' + 'CMAB decisions are dynamic and not stored for sticky bucketing.' + ) + + def test_get_variation_standard_experiment_saves_user_profile(self): + """Test that standard (non-CMAB) experiments DO save bucketing decisions to user profile.""" + + user = optimizely_user_context.OptimizelyUserContext( + optimizely_client=None, + logger=None, + user_id="test_user", + user_attributes={} + ) + + # Create a user profile service and tracker + user_profile_service = user_profile.UserProfileService() + user_profile_tracker = user_profile.UserProfileTracker(user.user_id, user_profile_service) + + # Get a standard (non-CMAB) experiment + experiment = self.project_config.get_experiment_from_key("test_experiment") + + with mock.patch('optimizely.decision_service.DecisionService.get_whitelisted_variation', + return_value=[None, []]), \ + mock.patch('optimizely.decision_service.DecisionService.get_stored_variation', + return_value=None), \ + mock.patch('optimizely.helpers.audience.does_user_meet_audience_conditions', + return_value=[True, []]), \ + mock.patch('optimizely.bucketer.Bucketer.bucket', + return_value=[entities.Variation("111129", "variation"), []]), \ + mock.patch.object(user_profile_tracker, 'update_user_profile') as mock_update_profile: + + # Call get_variation with standard experiment and user profile tracker + variation_result = self.decision_service.get_variation( + self.project_config, + experiment, + user, + user_profile_tracker + ) + variation = variation_result['variation'] + + # Verify variation was returned + self.assertEqual(entities.Variation("111129", "variation"), variation) + + # Verify user profile WAS updated for standard experiment + mock_update_profile.assert_called_once_with(experiment, variation) + class FeatureFlagDecisionTests(base.BaseTest): def setUp(self): From f98886af41e22d3d565c880b8e98efb054ae641a Mon Sep 17 00:00:00 2001 From: esrakartalOpt <102107327+esrakartalOpt@users.noreply.github.com> Date: Tue, 13 Jan 2026 15:56:55 -0600 Subject: [PATCH 11/32] [FSSDK-12149] [Python] Add Event Retries (#475) --- optimizely/event_dispatcher.py | 2 +- optimizely/odp/odp_event_manager.py | 9 ++++++++- tests/test_odp_event_manager.py | 12 ++++++++---- 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/optimizely/event_dispatcher.py b/optimizely/event_dispatcher.py index 55209dc8e..b06b9e187 100644 --- a/optimizely/event_dispatcher.py +++ b/optimizely/event_dispatcher.py @@ -49,7 +49,7 @@ def dispatch_event(event: event_builder.Event) -> None: session = requests.Session() retries = Retry(total=EventDispatchConfig.RETRIES, - backoff_factor=0.1, + backoff_factor=0.2, status_forcelist=[500, 502, 503, 504]) adapter = HTTPAdapter(max_retries=retries) diff --git a/optimizely/odp/odp_event_manager.py b/optimizely/odp/odp_event_manager.py index 85512e909..3fb961ac7 100644 --- a/optimizely/odp/odp_event_manager.py +++ b/optimizely/odp/odp_event_manager.py @@ -163,6 +163,8 @@ def _flush_batch(self) -> None: self.logger.debug(f'ODP event queue: flushing batch size {batch_len}.') should_retry = False + initial_retry_interval = 0.2 # 200ms + max_retry_interval = 1.0 # 1 second for i in range(1 + self.retry_count): try: @@ -176,7 +178,12 @@ def _flush_batch(self) -> None: if not should_retry: break if i < self.retry_count: - self.logger.debug('Error dispatching ODP events, scheduled to retry.') + # Exponential backoff: 200ms, 400ms, 800ms, ... capped at 1s + delay = initial_retry_interval * (2 ** i) + if delay > max_retry_interval: + delay = max_retry_interval + self.logger.debug(f'Error dispatching ODP events, retrying after {delay}s.') + time.sleep(delay) if should_retry: self.logger.error(Errors.ODP_EVENT_FAILED.format(f'Failed after {i} retries: {self._current_batch}')) diff --git a/tests/test_odp_event_manager.py b/tests/test_odp_event_manager.py index d9d29eabd..acec396f5 100644 --- a/tests/test_odp_event_manager.py +++ b/tests/test_odp_event_manager.py @@ -265,7 +265,7 @@ def test_odp_event_manager_retry_failure(self, *args): with mock.patch.object( event_manager.api_manager, 'send_odp_events', new_callable=CopyingMock, return_value=True - ) as mock_send: + ) as mock_send, mock.patch('time.sleep') as mock_sleep: event_manager.send_event(**self.events[0]) event_manager.send_event(**self.events[1]) event_manager.flush() @@ -275,7 +275,9 @@ def test_odp_event_manager_retry_failure(self, *args): [mock.call(self.api_key, self.api_host, self.processed_events)] * number_of_tries ) self.assertEqual(len(event_manager._current_batch), 0) - mock_logger.debug.assert_any_call('Error dispatching ODP events, scheduled to retry.') + # Verify exponential backoff delays: 0.2s, 0.4s, 0.8s + mock_sleep.assert_has_calls([mock.call(0.2), mock.call(0.4), mock.call(0.8)]) + mock_logger.debug.assert_any_call('Error dispatching ODP events, retrying after 0.2s.') mock_logger.error.assert_called_once_with( f'ODP event send failed (Failed after 3 retries: {self.processed_events}).' ) @@ -288,7 +290,7 @@ def test_odp_event_manager_retry_success(self, *args): with mock.patch.object( event_manager.api_manager, 'send_odp_events', new_callable=CopyingMock, side_effect=[True, True, False] - ) as mock_send: + ) as mock_send, mock.patch('time.sleep') as mock_sleep: event_manager.send_event(**self.events[0]) event_manager.send_event(**self.events[1]) event_manager.flush() @@ -296,7 +298,9 @@ def test_odp_event_manager_retry_success(self, *args): mock_send.assert_has_calls([mock.call(self.api_key, self.api_host, self.processed_events)] * 3) self.assertEqual(len(event_manager._current_batch), 0) - mock_logger.debug.assert_any_call('Error dispatching ODP events, scheduled to retry.') + # Verify exponential backoff delays: 0.2s, 0.4s (only 2 delays for 3 attempts) + mock_sleep.assert_has_calls([mock.call(0.2), mock.call(0.4)]) + mock_logger.debug.assert_any_call('Error dispatching ODP events, retrying after 0.2s.') mock_logger.error.assert_not_called() self.assertStrictTrue(event_manager.is_running) event_manager.stop() From 494e18b4134c43f375c106433288e438e7df1934 Mon Sep 17 00:00:00 2001 From: Farhan Anjum Date: Tue, 10 Feb 2026 22:11:41 +0600 Subject: [PATCH 12/32] [FSSDK-12276] update: replace flake8 with ruff (#492) * Add Ruff configuration file * Update target version in Ruff configuration to Python 3.9 * Replace Flake8 with Ruff for linting in CI and update contribution guidelines * Remove Flake8 configuration file as part of replacing Flake8 with Ruff * ruff autofix * testing ruff fail in ci * Fix formatting in ruff.toml by ensuring newline at end of file * Update .github/workflows/python.yml Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * ruff fix --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .flake8 | 8 ------- .github/workflows/python.yml | 15 +++++-------- CONTRIBUTING.md | 6 +++--- optimizely/helpers/validator.py | 4 ++-- requirements/test.txt | 2 +- ruff.toml | 38 +++++++++++++++++++++++++++++++++ 6 files changed, 49 insertions(+), 24 deletions(-) delete mode 100644 .flake8 create mode 100644 ruff.toml diff --git a/.flake8 b/.flake8 deleted file mode 100644 index 0fc0cadc0..000000000 --- a/.flake8 +++ /dev/null @@ -1,8 +0,0 @@ -[flake8] -# E722 - do not use bare 'except' -# W504 - Either W503 (Line break after Operand) or W503 ( -# Line break before operand needs to be ignored for line lengths -# greater than max-line-length. Best practice shows W504 -ignore = E722, W504 -exclude = optimizely/lib/pymmh3.py,*virtualenv*,tests/testapp/application.py -max-line-length = 120 diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 24d95e6a0..20894bbb1 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -33,17 +33,12 @@ jobs: uses: actions/setup-python@v4 with: python-version: '3.12' - # flake8 version should be same as the version in requirements/test.txt - # to avoid lint errors on CI - - name: pip install flak8 - run: pip install flake8>=4.1.0 - - name: Lint with flake8 + - name: Install dependencies for linting run: | - flake8 - # stop the build if there are Python syntax errors or undefined names - flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics - # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide - flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics + python -m pip install --upgrade pip + pip install -r requirements/test.txt + - name: Lint with Ruff + run: ruff check . integration_tests: uses: optimizely/python-sdk/.github/workflows/integration_test.yml@master diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d14002e15..9c1497108 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -15,7 +15,7 @@ Development process 2. Please follow the [commit message guidelines](https://github.com/angular/angular/blob/master/CONTRIBUTING.md#-commit-message-guidelines) for each commit message. 3. Make sure to add tests! -4. Run `flake8` to ensure there are no lint errors. +4. Run `ruff check .` to ensure there are no lint errors. 5. `git push` your changes to GitHub. 6. Open a PR from your fork into the master branch of the original repo. @@ -34,12 +34,12 @@ Pull request acceptance criteria - Tests are located in `/tests` with one file per class. - Please don't change the `__version__`. We'll take care of bumping the version when we next release. -- Lint your code with Flake8 before submitting. +- Lint your code with Ruff before submitting. Style ----- -We enforce Flake8 rules. +We enforce Ruff linting rules (Flake8-equivalent: pycodestyle + Pyflakes). License ------- diff --git a/optimizely/helpers/validator.py b/optimizely/helpers/validator.py index b9e4fcc52..593283314 100644 --- a/optimizely/helpers/validator.py +++ b/optimizely/helpers/validator.py @@ -193,7 +193,7 @@ def is_user_profile_valid(user_profile: dict[str, Any]) -> bool: if not user_profile: return False - if not type(user_profile) is dict: + if type(user_profile) is not dict: return False if UserProfile.USER_ID_KEY not in user_profile: @@ -203,7 +203,7 @@ def is_user_profile_valid(user_profile: dict[str, Any]) -> bool: return False experiment_bucket_map = user_profile.get(UserProfile.EXPERIMENT_BUCKET_MAP_KEY) - if not type(experiment_bucket_map) is dict: + if type(experiment_bucket_map) is not dict: return False for decision in experiment_bucket_map.values(): diff --git a/requirements/test.txt b/requirements/test.txt index c2e086c8e..c54f5bfa6 100644 --- a/requirements/test.txt +++ b/requirements/test.txt @@ -1,5 +1,5 @@ coverage -flake8 >= 4.0.1 +ruff >= 0.15.0 funcsigs >= 0.4 pytest >= 6.2.0 pytest-cov diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 000000000..5365a7b4d --- /dev/null +++ b/ruff.toml @@ -0,0 +1,38 @@ +# Ruff configuration +# https://docs.astral.sh/ruff/configuration/ + +line-length = 120 +target-version = "py39" + +exclude = [ + ".git", + ".venv", + "__pycache__", + "build", + "dist", + "*.egg-info", + "*virtualenv*", + "optimizely/lib/pymmh3.py", + "tests/testapp/application.py", +] + +[lint] +# Flake8-equivalent rules: +# E, W = pycodestyle (style errors & warnings) +# F = Pyflakes (logic errors, undefined names, unused imports) +select = ["E", "W", "F"] + +# Match current flake8 ignores +# E722 - do not use bare 'except' +ignore = ["E722"] + +# Allow autofix for all rules +fixable = ["ALL"] +unfixable = [] + +[lint.per-file-ignores] +# Ignore unused imports in __init__ files +"__init__.py" = ["F401"] + +[lint.isort] +known-first-party = ["optimizely"] From da4caeba4604859507f943aba5dfd09c4b7996a4 Mon Sep 17 00:00:00 2001 From: Farhan Anjum Date: Mon, 23 Feb 2026 22:41:34 +0600 Subject: [PATCH 13/32] [FSSDK-12320] bugfix: PollingConfigManager rejects valid URL-only configuration (#497) * fix: update PollingConfigManager initialization requirements and enhance tests for url handling * fix: clarify initialization requirements for PollingConfigManager --- optimizely/config_manager.py | 3 --- tests/test_config_manager.py | 32 +++++++++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/optimizely/config_manager.py b/optimizely/config_manager.py index 3dce27412..21c749733 100644 --- a/optimizely/config_manager.py +++ b/optimizely/config_manager.py @@ -236,9 +236,6 @@ def __init__( ) self._sdk_key = sdk_key or self._sdk_key - if self._sdk_key is None: - raise optimizely_exceptions.InvalidInputException(enums.Errors.MISSING_SDK_KEY) - self.datafile_url = self.get_datafile_url( self._sdk_key, url, url_template or self.DATAFILE_URL_TEMPLATE ) diff --git a/tests/test_config_manager.py b/tests/test_config_manager.py index 1930520e8..0e8cb7b30 100644 --- a/tests/test_config_manager.py +++ b/tests/test_config_manager.py @@ -224,12 +224,34 @@ def test_init__no_sdk_key_no_datafile__fails(self, _): """ Test that initialization fails if there is no sdk_key or datafile provided. """ self.assertRaisesRegex( optimizely_exceptions.InvalidInputException, - enums.Errors.MISSING_SDK_KEY, + 'Must provide at least one of sdk_key or url.', config_manager.PollingConfigManager, sdk_key=None, datafile=None, ) + def test_init__url_only__succeeds(self, _): + """ Test that initialization succeeds when only url is provided (no sdk_key). """ + test_url = 'https://mydatafiles.com/my_datafile.json' + test_headers = {'Last-Modified': 'New Time'} + test_datafile = json.dumps(self.config_dict_with_features) + test_response = requests.Response() + test_response.status_code = 200 + test_response.headers = test_headers + test_response._content = test_datafile + + with mock.patch('requests.Session.get', return_value=test_response) as mock_request: + project_config_manager = config_manager.PollingConfigManager(url=test_url) + project_config_manager.stop() + + mock_request.assert_called_once_with( + test_url, + headers={}, + timeout=enums.ConfigManager.REQUEST_TIMEOUT + ) + self.assertEqual(test_url, project_config_manager.datafile_url) + self.assertIsInstance(project_config_manager.get_config(), project_config.ProjectConfig) + def test_get_datafile_url__no_sdk_key_no_url_raises(self, _): """ Test that get_datafile_url raises exception if no sdk_key or url is provided. """ self.assertRaisesRegex( @@ -273,6 +295,14 @@ def test_get_datafile_url__sdk_key_and_template_provided(self, _): expected_url, config_manager.PollingConfigManager.get_datafile_url(test_sdk_key, None, test_url_template), ) + def test_get_datafile_url__url_provided(self, _): + """ Test get_datafile_url when only url is provided (no sdk_key). """ + test_url = 'www.myoptimizelydatafiles.com/my_key.json' + # url_template is ignored when url is provided + self.assertEqual( + test_url, config_manager.PollingConfigManager.get_datafile_url(None, test_url, None), + ) + def test_get_datafile_url__url_and_template_provided(self, _): """ Test get_datafile_url when url and url_template are provided. """ test_url_template = 'www.optimizelydatafiles.com/{sdk_key}.json' From d6519113a1f522cb6ede15a9574fcc267e2ccf45 Mon Sep 17 00:00:00 2001 From: Farhan Anjum Date: Fri, 27 Feb 2026 01:16:34 +0600 Subject: [PATCH 14/32] [FSSDK-12317] update: clear arnica risks (#498) * chore: remove outdated source clear GitHub Actions workflow * chore: add persist-credentials option to checkout steps in workflows --- .github/workflows/integration_test.yml | 1 + .github/workflows/python.yml | 8 ++++++++ .github/workflows/source_clear_cron.yml | 16 ---------------- 3 files changed, 9 insertions(+), 16 deletions(-) delete mode 100644 .github/workflows/source_clear_cron.yml diff --git a/.github/workflows/integration_test.yml b/.github/workflows/integration_test.yml index 7619ca51e..bc08c2cb8 100644 --- a/.github/workflows/integration_test.yml +++ b/.github/workflows/integration_test.yml @@ -17,6 +17,7 @@ jobs: steps: - uses: actions/checkout@v3 with: + persist-credentials: false # You should create a personal access token and store it in your repository token: ${{ secrets.CI_USER_TOKEN }} repository: 'optimizely/travisci-tools' diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 20894bbb1..830ca0f44 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -14,6 +14,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 + with: + persist-credentials: false - name: Set up Ruby uses: ruby/setup-ruby@v1 with: @@ -29,6 +31,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 + with: + persist-credentials: false - name: Set up Python 3.12 uses: actions/setup-python@v4 with: @@ -68,6 +72,8 @@ jobs: - "3.12" steps: - uses: actions/checkout@v3 + with: + persist-credentials: false - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: @@ -95,6 +101,8 @@ jobs: - "3.12" steps: - uses: actions/checkout@v3 + with: + persist-credentials: false - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: diff --git a/.github/workflows/source_clear_cron.yml b/.github/workflows/source_clear_cron.yml deleted file mode 100644 index 862b4a3f9..000000000 --- a/.github/workflows/source_clear_cron.yml +++ /dev/null @@ -1,16 +0,0 @@ -name: Source clear - -on: - schedule: - # Runs "weekly" - - cron: '0 0 * * 0' - -jobs: - source_clear: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - name: Source clear scan - env: - SRCCLR_API_TOKEN: ${{ secrets.SRCCLR_API_TOKEN }} - run: curl -sSL https://download.sourceclear.com/ci.sh | bash -s – scan From 55924e5a3e157e627a8e7b5b3c6df19d5a48ffc8 Mon Sep 17 00:00:00 2001 From: Farhan Anjum Date: Tue, 31 Mar 2026 01:57:52 +0600 Subject: [PATCH 15/32] [AI-FSSDK] [FSSDK-12337] Add Feature Rollout support (#499) * [AI-FSSDK] [FSSDK-12337] Add Feature Rollout support to project config parsing * [AI-FSSDK] [FSSDK-12337] Fix test structure, mypy and ruff compliance - Move feature rollout tests from standalone test_feature_rollout.py into test_config.py following module-level testing convention - Use base.BaseTest instead of unittest.TestCase for consistency - Fix mypy strict type errors in Variation construction using cast - All checks pass: ruff, mypy --strict, pytest (941/941) Co-Authored-By: Claude Opus 4.6 (1M context) * [AI-FSSDK] [FSSDK-12337] Simplify feature rollout config parsing - Inline _get_everyone_else_variation logic, remove unnecessary static method - Use get_rollout_from_id() to match TDD pseudocode - Remove isinstance check (rollout experiments are always dicts) - Remove 3 unit tests for deleted helper method (edge cases already covered by integration-level tests) Co-Authored-By: Claude Opus 4.6 (1M context) * [AI-FSSDK] [FSSDK-12337] Restore _get_everyone_else_variation as method - Restore as instance method matching TDD pseudocode structure - Takes flag (FeatureFlag) param, calls get_rollout_from_id internally - Caller simplified to: everyone_else_variation = self._get_everyone_else_variation(flag) * [AI-FSSDK] [FSSDK-12337] Add ExperimentTypes constants for type field - Add ExperimentTypes enum in helpers/enums.py with AB, MAB, CMAB, FEATURE_ROLLOUT - Use ExperimentTypes.FEATURE_ROLLOUT constant in config parsing instead of raw string * [AI-FSSDK] [FSSDK-12337] Type-restrict Experiment.type to ExperimentType - Add ExperimentType Literal type in helpers/types.py: 'a/b', 'mab', 'cmab', 'feature_rollout' - Change Experiment.type from Optional[str] to Optional[ExperimentType] * [AI-FSSDK] [FSSDK-12337] Remove ExperimentTypes class, simplify type check - Remove redundant ExperimentTypes class from enums.py (ExperimentType Literal suffices) - Simplify getattr(experiment, 'type', None) to experiment.type * [AI-FSSDK] [FSSDK-12337] Return Variation entity from _get_everyone_else_variation - Build Variation entity once in helper, derive dict from it in caller - Addresses PR review comment from jaeopt * [AI-FSSDK] [FSSDK-12337] Remove redundant tests, keep 6 essential ones Removed 7 tests that were covered by other tests: - test_experiment_type_field_parsed (covered by injection test) - test_feature_rollout_with_empty_rollout_experiments (similar to no_rollout) - test_feature_rollout_multiple_experiments_mixed_types (covered by injection + unchanged) - test_feature_rollout_flag_variations_map_includes_injected (subset of maps test) - test_experiment_type_ab (just string assignment) - test_feature_rollout_with_variables_on_everyone_else (edge case) - test_existing_datafile_not_broken (covered by none_when_missing + unchanged) * [AI-FSSDK] [FSSDK-12337] Add ExperimentTypes constant and targeted_delivery type - Add ExperimentTypes class in enums.py with ab, mab, cmab, td, fr - Add 'targeted_delivery' to ExperimentType Literal in types.py - Use enums.ExperimentTypes.fr constant in injection check - Add test for type field parsing from datafile * [AI-FSSDK] [FSSDK-12337] Remove test not in ticket spec Remove test_feature_rollout_everyone_else_is_last_rollout_rule to match updated Jira ticket test requirements. * [FSSDK-12337] Fix experiment type values to match backend Update ExperimentTypes and ExperimentType Literal to use actual backend values: 'multi_armed_bandit' and 'contextual_multi_armed_bandit' instead of shorthand 'mab' and 'cmab'. * Format ExperimentType definition for ruff check * [AI-FSSDK] [FSSDK-12337] Update experiment type values to short-form abbreviations * [AI-FSSDK] [FSSDK-12337] Add validation for experiment type field * trigger CI --------- Co-authored-by: Claude Opus 4.6 (1M context) --- optimizely/entities.py | 4 +- optimizely/helpers/enums.py | 8 + optimizely/helpers/types.py | 4 + optimizely/project_config.py | 83 ++++++++ tests/test_config.py | 363 +++++++++++++++++++++++++++++++++++ 5 files changed, 461 insertions(+), 1 deletion(-) diff --git a/optimizely/entities.py b/optimizely/entities.py index 12f4f8495..6aa0060dd 100644 --- a/optimizely/entities.py +++ b/optimizely/entities.py @@ -22,7 +22,7 @@ if TYPE_CHECKING: # prevent circular dependenacy by skipping import at runtime - from .helpers.types import ExperimentDict, TrafficAllocation, VariableDict, VariationDict, CmabDict + from .helpers.types import ExperimentDict, ExperimentType, TrafficAllocation, VariableDict, VariationDict, CmabDict class BaseEntity: @@ -87,6 +87,7 @@ def __init__( groupId: Optional[str] = None, groupPolicy: Optional[str] = None, cmab: Optional[CmabDict] = None, + type: Optional[ExperimentType] = None, **kwargs: Any ): self.id = id @@ -101,6 +102,7 @@ def __init__( self.groupId = groupId self.groupPolicy = groupPolicy self.cmab = cmab + self.type = type def get_audience_conditions_or_ids(self) -> Sequence[str | list[str]]: """ Returns audienceConditions if present, otherwise audienceIds. """ diff --git a/optimizely/helpers/enums.py b/optimizely/helpers/enums.py index 74acdcfa6..2d1d46764 100644 --- a/optimizely/helpers/enums.py +++ b/optimizely/helpers/enums.py @@ -229,6 +229,14 @@ class OdpManagerConfig: EVENT_TYPE: Final = 'fullstack' +class ExperimentTypes: + ab: Final = 'ab' + mab: Final = 'mab' + cmab: Final = 'cmab' + td: Final = 'td' + fr: Final = 'fr' + + class OdpSegmentsCacheConfig: """ODP Segment Cache configs.""" DEFAULT_CAPACITY: Final = 10_000 diff --git a/optimizely/helpers/types.py b/optimizely/helpers/types.py index d4177dc0b..7076dc4d0 100644 --- a/optimizely/helpers/types.py +++ b/optimizely/helpers/types.py @@ -117,6 +117,10 @@ class CmabDict(BaseEntity): trafficAllocation: int +ExperimentType = Literal[ + 'ab', 'mab', 'cmab', 'td', 'fr' +] + HoldoutStatus = Literal['Draft', 'Running', 'Concluded', 'Archived'] diff --git a/optimizely/project_config.py b/optimizely/project_config.py index 74442d7ac..3aa1cc2b9 100644 --- a/optimizely/project_config.py +++ b/optimizely/project_config.py @@ -189,7 +189,24 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): self.variation_key_map_by_experiment_id: dict[str, dict[str, Union[entities.Variation, VariationDict]]] = {} self.flag_variations_map: dict[str, list[entities.Variation]] = {} + valid_experiment_types = { + enums.ExperimentTypes.ab, + enums.ExperimentTypes.mab, + enums.ExperimentTypes.cmab, + enums.ExperimentTypes.td, + enums.ExperimentTypes.fr, + } for experiment in self.experiment_id_map.values(): + if experiment.type is not None and experiment.type not in valid_experiment_types: + self.logger.error( + f'Experiment "{experiment.key}" has invalid type "{experiment.type}". ' + f'Valid types: {valid_experiment_types}.' + ) + self.error_handler.handle_error( + exceptions.InvalidExperimentException( + f'Invalid experiment type: {experiment.type}' + ) + ) self.experiment_key_map[experiment.key] = experiment self.variation_key_map[experiment.key] = self._generate_key_map( experiment.variations, 'key', entities.Variation @@ -232,6 +249,37 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): self.experiment_feature_map[exp_id] = [feature.id] rules.append(self.experiment_id_map[exp_id]) + # Feature Rollout support: inject the "everyone else" variation + # into any experiment with type == "feature_rollout" + everyone_else_variation = self._get_everyone_else_variation(feature) + if everyone_else_variation is not None: + for experiment in rules: + if experiment.type == enums.ExperimentTypes.fr: + experiment.variations.append({ + 'id': everyone_else_variation.id, + 'key': everyone_else_variation.key, + 'featureEnabled': everyone_else_variation.featureEnabled, + 'variables': cast( + list[types.VariableDict], + everyone_else_variation.variables, + ), + }) + experiment.trafficAllocation.append({ + 'entityId': everyone_else_variation.id, + 'endOfRange': 10000, + }) + self.variation_key_map[experiment.key][everyone_else_variation.key] = everyone_else_variation + self.variation_id_map[experiment.key][everyone_else_variation.id] = everyone_else_variation + self.variation_id_map_by_experiment_id[experiment.id][everyone_else_variation.id] = ( + everyone_else_variation + ) + self.variation_key_map_by_experiment_id[experiment.id][everyone_else_variation.key] = ( + everyone_else_variation + ) + self.variation_variable_usage_map[everyone_else_variation.id] = self._generate_key_map( + everyone_else_variation.variables, 'id', entities.Variation.VariableUsage + ) + flag_id = feature.id applicable_holdouts: list[entities.Holdout] = [] @@ -667,6 +715,41 @@ def get_rollout_from_id(self, rollout_id: str) -> Optional[entities.Layer]: self.logger.error(f'Rollout with ID "{rollout_id}" is not in datafile.') return None + def _get_everyone_else_variation(self, flag: entities.FeatureFlag) -> Optional[entities.Variation]: + """ Get the "everyone else" variation for a feature flag. + + The "everyone else" rule is the last experiment in the flag's rollout, + and its first variation is the "everyone else" variation. + + Args: + flag: The feature flag to get the everyone else variation for. + + Returns: + The "everyone else" Variation entity, or None if not available. + """ + if not flag.rolloutId: + return None + + rollout = self.get_rollout_from_id(flag.rolloutId) + if not rollout or not rollout.experiments: + return None + + everyone_else_rule = rollout.experiments[-1] + variations = everyone_else_rule.get('variations', []) + if not variations: + return None + + variation_dict = variations[0] + return entities.Variation( + id=variation_dict['id'], + key=variation_dict['key'], + featureEnabled=bool(variation_dict.get('featureEnabled', False)), + variables=cast( + Optional[list[entities.Variable]], + variation_dict.get('variables'), + ), + ) + def get_variable_value_for_variation( self, variable: Optional[entities.Variable], variation: Optional[Union[entities.Variation, VariationDict]] ) -> Optional[str]: diff --git a/tests/test_config.py b/tests/test_config.py index 81228febf..eba36bc4a 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1545,3 +1545,366 @@ def test_holdout_initialization__only_processes_running_holdouts(self): boolean_feature_id = '91111' included_for_boolean = self.config_with_holdouts.included_holdouts.get(boolean_feature_id) self.assertIsNone(included_for_boolean) + + +class FeatureRolloutConfigTest(base.BaseTest): + """Tests for Feature Rollout support in ProjectConfig parsing.""" + + def _build_datafile(self, experiments=None, rollouts=None, feature_flags=None): + """Build a minimal valid datafile with the given components.""" + datafile = { + 'version': '4', + 'accountId': '12001', + 'projectId': '111001', + 'revision': '1', + 'experiments': experiments or [], + 'events': [], + 'attributes': [], + 'audiences': [], + 'groups': [], + 'rollouts': rollouts or [], + 'featureFlags': feature_flags or [], + } + return datafile + + def test_experiment_type_field_parsed(self): + """Test that the 'type' field value is preserved on Experiment after config parsing.""" + datafile = self._build_datafile( + experiments=[ + { + 'id': 'exp_1', + 'key': 'feature_rollout_exp', + 'status': 'Running', + 'forcedVariations': {}, + 'layerId': 'layer_1', + 'audienceIds': [], + 'trafficAllocation': [{'entityId': 'var_1', 'endOfRange': 5000}], + 'variations': [{'key': 'var_1', 'id': 'var_1', 'featureEnabled': True}], + 'type': 'fr', + }, + ], + rollouts=[ + { + 'id': 'rollout_1', + 'experiments': [ + { + 'id': 'rollout_rule_1', + 'key': 'rollout_rule_1', + 'status': 'Running', + 'forcedVariations': {}, + 'layerId': 'rollout_1', + 'audienceIds': [], + 'trafficAllocation': [{'entityId': 'everyone_var', 'endOfRange': 10000}], + 'variations': [ + {'key': 'everyone_var', 'id': 'everyone_var', 'featureEnabled': False} + ], + } + ], + } + ], + feature_flags=[ + { + 'id': 'flag_1', + 'key': 'test_flag', + 'experimentIds': ['exp_1'], + 'rolloutId': 'rollout_1', + 'variables': [], + }, + ], + ) + + opt = optimizely.Optimizely(json.dumps(datafile)) + config = opt.config_manager.get_config() + + experiment = config.experiment_id_map['exp_1'] + self.assertEqual(experiment.type, 'fr') + + def test_experiment_type_field_none_when_missing(self): + """Test that experiments without 'type' field have type=None.""" + datafile = self._build_datafile( + experiments=[ + { + 'id': 'exp_ab', + 'key': 'ab_test_exp', + 'status': 'Running', + 'forcedVariations': {}, + 'layerId': 'layer_1', + 'audienceIds': [], + 'trafficAllocation': [{'entityId': 'var_1', 'endOfRange': 5000}], + 'variations': [{'key': 'var_1', 'id': 'var_1', 'featureEnabled': True}], + }, + ], + feature_flags=[ + { + 'id': 'flag_1', + 'key': 'test_flag', + 'experimentIds': ['exp_ab'], + 'rolloutId': '', + 'variables': [], + }, + ], + ) + + opt = optimizely.Optimizely(json.dumps(datafile)) + config = opt.config_manager.get_config() + + experiment = config.experiment_id_map['exp_ab'] + self.assertIsNone(experiment.type) + + def test_feature_rollout_injects_everyone_else_variation(self): + """Test that feature_rollout experiments get the everyone else variation injected.""" + datafile = self._build_datafile( + experiments=[ + { + 'id': 'exp_fr', + 'key': 'feature_rollout_exp', + 'status': 'Running', + 'forcedVariations': {}, + 'layerId': 'layer_1', + 'audienceIds': [], + 'trafficAllocation': [{'entityId': 'rollout_var', 'endOfRange': 5000}], + 'variations': [ + {'key': 'rollout_var', 'id': 'rollout_var', 'featureEnabled': True} + ], + 'type': 'fr', + }, + ], + rollouts=[ + { + 'id': 'rollout_1', + 'experiments': [ + { + 'id': 'rollout_targeted_rule', + 'key': 'rollout_targeted_rule', + 'status': 'Running', + 'forcedVariations': {}, + 'layerId': 'rollout_1', + 'audienceIds': ['audience_1'], + 'trafficAllocation': [{'entityId': 'targeted_var', 'endOfRange': 10000}], + 'variations': [ + {'key': 'targeted_var', 'id': 'targeted_var', 'featureEnabled': True} + ], + }, + { + 'id': 'rollout_everyone_else', + 'key': 'rollout_everyone_else', + 'status': 'Running', + 'forcedVariations': {}, + 'layerId': 'rollout_1', + 'audienceIds': [], + 'trafficAllocation': [ + {'entityId': 'everyone_else_var', 'endOfRange': 10000} + ], + 'variations': [ + { + 'key': 'everyone_else_var', + 'id': 'everyone_else_var', + 'featureEnabled': False, + } + ], + }, + ], + } + ], + feature_flags=[ + { + 'id': 'flag_1', + 'key': 'test_flag', + 'experimentIds': ['exp_fr'], + 'rolloutId': 'rollout_1', + 'variables': [], + }, + ], + ) + + opt = optimizely.Optimizely(json.dumps(datafile)) + config = opt.config_manager.get_config() + + experiment = config.experiment_id_map['exp_fr'] + + # Should now have 2 variations: original + everyone else + self.assertEqual(len(experiment.variations), 2) + + # Verify the everyone else variation was appended + variation_ids = [v['id'] if isinstance(v, dict) else v.id for v in experiment.variations] + self.assertIn('everyone_else_var', variation_ids) + + # Verify traffic allocation was appended with endOfRange=10000 + self.assertEqual(len(experiment.trafficAllocation), 2) + last_allocation = experiment.trafficAllocation[-1] + self.assertEqual(last_allocation['entityId'], 'everyone_else_var') + self.assertEqual(last_allocation['endOfRange'], 10000) + + def test_feature_rollout_variation_maps_updated(self): + """Test that variation maps are properly updated after injection.""" + datafile = self._build_datafile( + experiments=[ + { + 'id': 'exp_fr', + 'key': 'feature_rollout_exp', + 'status': 'Running', + 'forcedVariations': {}, + 'layerId': 'layer_1', + 'audienceIds': [], + 'trafficAllocation': [{'entityId': 'rollout_var', 'endOfRange': 5000}], + 'variations': [ + {'key': 'rollout_var', 'id': 'rollout_var', 'featureEnabled': True} + ], + 'type': 'fr', + }, + ], + rollouts=[ + { + 'id': 'rollout_1', + 'experiments': [ + { + 'id': 'rollout_everyone_else', + 'key': 'rollout_everyone_else', + 'status': 'Running', + 'forcedVariations': {}, + 'layerId': 'rollout_1', + 'audienceIds': [], + 'trafficAllocation': [ + {'entityId': 'everyone_else_var', 'endOfRange': 10000} + ], + 'variations': [ + { + 'key': 'everyone_else_var', + 'id': 'everyone_else_var', + 'featureEnabled': False, + } + ], + }, + ], + } + ], + feature_flags=[ + { + 'id': 'flag_1', + 'key': 'test_flag', + 'experimentIds': ['exp_fr'], + 'rolloutId': 'rollout_1', + 'variables': [], + }, + ], + ) + + opt = optimizely.Optimizely(json.dumps(datafile)) + config = opt.config_manager.get_config() + + # Check variation_key_map is updated + self.assertIn('everyone_else_var', config.variation_key_map['feature_rollout_exp']) + + # Check variation_id_map is updated + self.assertIn('everyone_else_var', config.variation_id_map['feature_rollout_exp']) + + # Check variation_id_map_by_experiment_id is updated + self.assertIn('everyone_else_var', config.variation_id_map_by_experiment_id['exp_fr']) + + # Check variation_key_map_by_experiment_id is updated + self.assertIn('everyone_else_var', config.variation_key_map_by_experiment_id['exp_fr']) + + def test_non_feature_rollout_experiments_unchanged(self): + """Test that experiments without type=feature_rollout are not modified.""" + datafile = self._build_datafile( + experiments=[ + { + 'id': 'exp_ab', + 'key': 'ab_test_exp', + 'status': 'Running', + 'forcedVariations': {}, + 'layerId': 'layer_1', + 'audienceIds': [], + 'trafficAllocation': [{'entityId': 'var_1', 'endOfRange': 5000}], + 'variations': [ + {'key': 'var_1', 'id': 'var_1', 'featureEnabled': True} + ], + 'type': 'ab', + }, + ], + rollouts=[ + { + 'id': 'rollout_1', + 'experiments': [ + { + 'id': 'rollout_everyone_else', + 'key': 'rollout_everyone_else', + 'status': 'Running', + 'forcedVariations': {}, + 'layerId': 'rollout_1', + 'audienceIds': [], + 'trafficAllocation': [ + {'entityId': 'everyone_else_var', 'endOfRange': 10000} + ], + 'variations': [ + { + 'key': 'everyone_else_var', + 'id': 'everyone_else_var', + 'featureEnabled': False, + } + ], + }, + ], + } + ], + feature_flags=[ + { + 'id': 'flag_1', + 'key': 'test_flag', + 'experimentIds': ['exp_ab'], + 'rolloutId': 'rollout_1', + 'variables': [], + }, + ], + ) + + opt = optimizely.Optimizely(json.dumps(datafile)) + config = opt.config_manager.get_config() + + experiment = config.experiment_id_map['exp_ab'] + + # Should still have only 1 variation + self.assertEqual(len(experiment.variations), 1) + # Should still have only 1 traffic allocation + self.assertEqual(len(experiment.trafficAllocation), 1) + + def test_feature_rollout_with_no_rollout(self): + """Test feature_rollout experiment with empty rolloutId is not modified.""" + datafile = self._build_datafile( + experiments=[ + { + 'id': 'exp_fr', + 'key': 'feature_rollout_exp', + 'status': 'Running', + 'forcedVariations': {}, + 'layerId': 'layer_1', + 'audienceIds': [], + 'trafficAllocation': [{'entityId': 'var_1', 'endOfRange': 5000}], + 'variations': [ + {'key': 'var_1', 'id': 'var_1', 'featureEnabled': True} + ], + 'type': 'fr', + }, + ], + feature_flags=[ + { + 'id': 'flag_1', + 'key': 'test_flag', + 'experimentIds': ['exp_fr'], + 'rolloutId': '', + 'variables': [], + }, + ], + ) + + opt = optimizely.Optimizely(json.dumps(datafile)) + config = opt.config_manager.get_config() + + experiment = config.experiment_id_map['exp_fr'] + + # Without a rollout, no injection should occur + self.assertEqual(len(experiment.variations), 1) + self.assertEqual(len(experiment.trafficAllocation), 1) + + + From 54ae4c6bd51d9a1475b2af04b02060d64d700162 Mon Sep 17 00:00:00 2001 From: Farhan Anjum Date: Wed, 8 Apr 2026 22:09:09 +0600 Subject: [PATCH 16/32] [AI-FSSDK] [FSSDK-12418] Remove experiment type validation from config parsing (#500) --- optimizely/entities.py | 4 ++-- optimizely/project_config.py | 17 ----------------- tests/test_config.py | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 19 deletions(-) diff --git a/optimizely/entities.py b/optimizely/entities.py index 6aa0060dd..589ca9847 100644 --- a/optimizely/entities.py +++ b/optimizely/entities.py @@ -22,7 +22,7 @@ if TYPE_CHECKING: # prevent circular dependenacy by skipping import at runtime - from .helpers.types import ExperimentDict, ExperimentType, TrafficAllocation, VariableDict, VariationDict, CmabDict + from .helpers.types import ExperimentDict, TrafficAllocation, VariableDict, VariationDict, CmabDict class BaseEntity: @@ -87,7 +87,7 @@ def __init__( groupId: Optional[str] = None, groupPolicy: Optional[str] = None, cmab: Optional[CmabDict] = None, - type: Optional[ExperimentType] = None, + type: Optional[str] = None, **kwargs: Any ): self.id = id diff --git a/optimizely/project_config.py b/optimizely/project_config.py index 3aa1cc2b9..5b7525389 100644 --- a/optimizely/project_config.py +++ b/optimizely/project_config.py @@ -189,24 +189,7 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): self.variation_key_map_by_experiment_id: dict[str, dict[str, Union[entities.Variation, VariationDict]]] = {} self.flag_variations_map: dict[str, list[entities.Variation]] = {} - valid_experiment_types = { - enums.ExperimentTypes.ab, - enums.ExperimentTypes.mab, - enums.ExperimentTypes.cmab, - enums.ExperimentTypes.td, - enums.ExperimentTypes.fr, - } for experiment in self.experiment_id_map.values(): - if experiment.type is not None and experiment.type not in valid_experiment_types: - self.logger.error( - f'Experiment "{experiment.key}" has invalid type "{experiment.type}". ' - f'Valid types: {valid_experiment_types}.' - ) - self.error_handler.handle_error( - exceptions.InvalidExperimentException( - f'Invalid experiment type: {experiment.type}' - ) - ) self.experiment_key_map[experiment.key] = experiment self.variation_key_map[experiment.key] = self._generate_key_map( experiment.variations, 'key', entities.Variation diff --git a/tests/test_config.py b/tests/test_config.py index eba36bc4a..c21f9b349 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1651,6 +1651,41 @@ def test_experiment_type_field_none_when_missing(self): experiment = config.experiment_id_map['exp_ab'] self.assertIsNone(experiment.type) + def test_unknown_experiment_type_accepted(self): + """Test that experiments with unknown type values are accepted without error.""" + datafile = self._build_datafile( + experiments=[ + { + 'id': 'exp_unknown', + 'key': 'unknown_type_exp', + 'status': 'Running', + 'forcedVariations': {}, + 'layerId': 'layer_1', + 'audienceIds': [], + 'trafficAllocation': [{'entityId': 'var_1', 'endOfRange': 5000}], + 'variations': [{'key': 'var_1', 'id': 'var_1', 'featureEnabled': True}], + 'type': 'new_unknown_type', + }, + ], + feature_flags=[ + { + 'id': 'flag_1', + 'key': 'test_flag', + 'experimentIds': ['exp_unknown'], + 'rolloutId': '', + 'variables': [], + }, + ], + ) + + opt = optimizely.Optimizely(json.dumps(datafile)) + config = opt.config_manager.get_config() + + self.assertIsNotNone(config) + experiment = config.experiment_id_map['exp_unknown'] + self.assertEqual(experiment.type, 'new_unknown_type') + self.assertEqual(experiment.key, 'unknown_type_exp') + def test_feature_rollout_injects_everyone_else_variation(self): """Test that feature_rollout experiments get the everyone else variation injected.""" datafile = self._build_datafile( From f02b3ce1cf38382a46f0d90f2dbe3ec4c282df65 Mon Sep 17 00:00:00 2001 From: Farhan Anjum Date: Fri, 17 Apr 2026 14:52:56 +0600 Subject: [PATCH 17/32] [FSSDK-12497] Fix return in finally block silently swallowing exceptions (#505) Move error-handling logic out of finally block into normal control flow and change bare except to except Exception. Per Python docs, a return in finally suppresses any in-flight exception, which silently swallows errors raised inside except blocks. Fixes https://github.com/optimizely/python-sdk/issues/439 Co-authored-by: Claude Opus 4.6 (1M context) --- optimizely/config_manager.py | 12 ++++++------ tests/test_config_manager.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/optimizely/config_manager.py b/optimizely/config_manager.py index 21c749733..22468b05b 100644 --- a/optimizely/config_manager.py +++ b/optimizely/config_manager.py @@ -145,14 +145,14 @@ def _set_config(self, datafile: Optional[str | bytes]) -> None: except optimizely_exceptions.UnsupportedDatafileVersionException as error: error_msg = error.args[0] error_to_handle = error - except: + except Exception: error_msg = enums.Errors.INVALID_INPUT.format('datafile') error_to_handle = optimizely_exceptions.InvalidInputException(error_msg) - finally: - if error_msg or config is None: - self.logger.error(error_msg) - self.error_handler.handle_error(error_to_handle or Exception('Unknown Error')) - return + + if error_msg or config is None: + self.logger.error(error_msg) + self.error_handler.handle_error(error_to_handle or Exception('Unknown Error')) + return previous_revision = self._config.get_revision() if self._config else None diff --git a/tests/test_config_manager.py b/tests/test_config_manager.py index 0e8cb7b30..8fa196933 100644 --- a/tests/test_config_manager.py +++ b/tests/test_config_manager.py @@ -200,6 +200,36 @@ def test_set_config__invalid_datafile(self): mock_logger.error.assert_called_once_with('Provided "datafile" is in an invalid format.') self.assertEqual(0, mock_notification_center.call_count) + def test_set_config__exception_in_except_block_is_not_swallowed(self): + """ Test that an exception raised inside the except block propagates + to the caller instead of being silently swallowed. + + Per Python docs, a return inside a finally clause suppresses any + in-flight exception. The _set_config method must not use return in + finally, so that unexpected errors in the error-handling path are + surfaced rather than silently lost. + """ + test_datafile = json.dumps(self.config_dict_with_features) + mock_logger = mock.Mock() + + with mock.patch('optimizely.config_manager.BaseConfigManager._validate_instantiation_options'): + project_config_manager = config_manager.StaticConfigManager( + datafile=test_datafile, logger=mock_logger, + ) + + # Make ProjectConfig raise so we enter the bare except block, + # then make the except block itself raise by breaking INVALID_INPUT. + with mock.patch( + 'optimizely.project_config.ProjectConfig.__init__', + side_effect=Exception('something broke'), + ), mock.patch.object( + enums.Errors, 'INVALID_INPUT', new=None, + ): + # The except block will raise AttributeError ('NoneType' has no 'format'). + # Correct behavior: this exception must propagate to the caller. + with self.assertRaises(AttributeError): + project_config_manager._set_config(test_datafile) + def test_get_config(self): """ Test get_config. """ test_datafile = json.dumps(self.config_dict_with_features) From c05c09b375574da9ad48bdeaebe8ea614e28f129 Mon Sep 17 00:00:00 2001 From: Matjaz Pirnovar Date: Fri, 24 Apr 2026 08:01:03 -0700 Subject: [PATCH 18/32] [AI-FSSDK] [FSSDK-12368] Cleanup flag base setup (local holdouts) (#507) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [FSSDK-12368] Remove legacy flag-level holdout fields Remove deprecated flag-level holdout functionality as cleanup after local holdouts (FSSDK-12369) implementation. Changes: - Removed includedFlags and excludedFlags from Holdout entity - Removed includedFlags and excludedFlags from HoldoutDict type - Removed get_holdouts_for_flag() method from ProjectConfig - Removed flag-level holdout infrastructure: - global_holdouts list - included_holdouts dict - excluded_holdouts dict - flag_holdouts_map dict - Flag-level population logic in ProjectConfig.__init__ - Removed flag-level holdout checking from DecisionService.get_variation_for_feature() - Removed 10 test methods testing removed functionality - Removed includedFlags/excludedFlags from all test fixtures Impact: 7 files modified, 310 lines deleted, 5 lines added (net: -305 lines) Verification: - grep for "includedFlags", "excludedFlags", "getHoldoutsForFlag" returns zero results - grep for "global_holdouts", "included_holdouts", "excluded_holdouts", "flag_holdouts_map" returns zero results Co-Authored-By: Claude Sonnet 4.5 * [FSSDK-12368] Restore holdout evaluation in decide flow, remove only flag-level include/exclude fields The previous cleanup removed the entire holdout evaluation from the decide flow. This restores holdout checking while keeping the removal of legacy includedFlags/excludedFlags fields — all running holdouts now apply to all flags uniformly. Co-Authored-By: Claude Opus 4.6 (1M context) --------- Co-authored-by: Claude Sonnet 4.5 Co-authored-by: Farhan Anjum --- optimizely/entities.py | 4 - optimizely/helpers/types.py | 2 - optimizely/project_config.py | 40 +------- tests/test_bucketing_holdout.py | 4 - tests/test_config.py | 95 +---------------- tests/test_decision_service_holdout.py | 137 ------------------------- 6 files changed, 6 insertions(+), 276 deletions(-) diff --git a/optimizely/entities.py b/optimizely/entities.py index 589ca9847..f67dee893 100644 --- a/optimizely/entities.py +++ b/optimizely/entities.py @@ -222,8 +222,6 @@ def __init__( variations: list[VariationDict], trafficAllocation: list[TrafficAllocation], audienceIds: list[str], - includedFlags: Optional[list[str]] = None, - excludedFlags: Optional[list[str]] = None, audienceConditions: Optional[Sequence[str | list[str]]] = None, **kwargs: Any ): @@ -234,8 +232,6 @@ def __init__( self.trafficAllocation = trafficAllocation self.audienceIds = audienceIds self.audienceConditions = audienceConditions - self.includedFlags = includedFlags or [] - self.excludedFlags = excludedFlags or [] def get_audience_conditions_or_ids(self) -> Sequence[str | list[str]]: """Returns audienceConditions if present, otherwise audienceIds. diff --git a/optimizely/helpers/types.py b/optimizely/helpers/types.py index 7076dc4d0..6b704c363 100644 --- a/optimizely/helpers/types.py +++ b/optimizely/helpers/types.py @@ -130,5 +130,3 @@ class HoldoutDict(ExperimentDict): Extends ExperimentDict with holdout-specific properties. """ holdoutStatus: HoldoutStatus - includedFlags: list[str] - excludedFlags: list[str] diff --git a/optimizely/project_config.py b/optimizely/project_config.py index 5b7525389..0fb0f35f1 100644 --- a/optimizely/project_config.py +++ b/optimizely/project_config.py @@ -93,9 +93,6 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): holdouts_data: list[types.HoldoutDict] = config.get('holdouts', []) self.holdouts: list[entities.Holdout] = [] self.holdout_id_map: dict[str, entities.Holdout] = {} - self.global_holdouts: list[entities.Holdout] = [] - self.included_holdouts: dict[str, list[entities.Holdout]] = {} - self.excluded_holdouts: dict[str, list[entities.Holdout]] = {} self.flag_holdouts_map: dict[str, list[entities.Holdout]] = {} # Convert holdout dicts to Holdout entities @@ -104,33 +101,13 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): holdout = entities.Holdout(**holdout_data) self.holdouts.append(holdout) - # Only process Running holdouts but doing it here for efficiency like the original Python implementation) + # Only process Running holdouts if not holdout.is_activated: continue # Map by ID for quick lookup self.holdout_id_map[holdout.id] = holdout - # Categorize as global vs flag-specific - # Global holdouts: apply to all flags unless explicitly excluded - # Flag-specific holdouts: only apply to explicitly included flags - if not holdout.includedFlags: - # This is a global holdout - self.global_holdouts.append(holdout) - - # Track which flags this global holdout excludes - if holdout.excludedFlags: - for flag_id in holdout.excludedFlags: - if flag_id not in self.excluded_holdouts: - self.excluded_holdouts[flag_id] = [] - self.excluded_holdouts[flag_id].append(holdout) - else: - # This holdout applies to specific flags only - for flag_id in holdout.includedFlags: - if flag_id not in self.included_holdouts: - self.included_holdouts[flag_id] = [] - self.included_holdouts[flag_id].append(holdout) - # Utility maps for quick lookup self.group_id_map: dict[str, entities.Group] = self._generate_key_map(self.groups, 'id', entities.Group) self.experiment_id_map: dict[str, entities.Experiment] = self._generate_key_map( @@ -263,19 +240,8 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): everyone_else_variation.variables, 'id', entities.Variation.VariableUsage ) - flag_id = feature.id - applicable_holdouts: list[entities.Holdout] = [] - - # Add global holdouts first, excluding any that are explicitly excluded for this flag - excluded_holdouts = self.excluded_holdouts.get(flag_id, []) - for holdout in self.global_holdouts: - if holdout not in excluded_holdouts: - applicable_holdouts.append(holdout) - - # Add flag-specific local holdouts AFTER global holdouts - if flag_id in self.included_holdouts: - applicable_holdouts.extend(self.included_holdouts[flag_id]) - + # Map all running holdouts to this flag + applicable_holdouts = list(self.holdout_id_map.values()) if applicable_holdouts: self.flag_holdouts_map[feature.key] = applicable_holdouts diff --git a/tests/test_bucketing_holdout.py b/tests/test_bucketing_holdout.py index e3d9bcb30..8a5e7c78f 100644 --- a/tests/test_bucketing_holdout.py +++ b/tests/test_bucketing_holdout.py @@ -62,8 +62,6 @@ def setUp(self): 'id': 'holdout_1', 'key': 'test_holdout', 'status': 'Running', - 'includedFlags': [], - 'excludedFlags': [], 'audienceIds': [], 'variations': [ { @@ -92,8 +90,6 @@ def setUp(self): 'id': 'holdout_empty_1', 'key': 'empty_holdout', 'status': 'Running', - 'includedFlags': [], - 'excludedFlags': [], 'audienceIds': [], 'variations': [], 'trafficAllocation': [] diff --git a/tests/test_config.py b/tests/test_config.py index c21f9b349..29b1c49e3 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1384,10 +1384,6 @@ def setUp(self): # Create config with holdouts config_body_with_holdouts = self.config_dict_with_features.copy() - # Use correct feature flag IDs from the datafile - boolean_feature_id = '91111' # boolean_single_variable_feature - multi_variate_feature_id = '91114' # test_feature_in_experiment_and_rollout - config_body_with_holdouts['holdouts'] = [ { 'id': 'holdout_1', @@ -1395,9 +1391,7 @@ def setUp(self): 'status': 'Running', 'variations': [], 'trafficAllocation': [], - 'audienceIds': [], - 'includedFlags': [], - 'excludedFlags': [boolean_feature_id] + 'audienceIds': [] }, { 'id': 'holdout_2', @@ -1405,9 +1399,7 @@ def setUp(self): 'status': 'Running', 'variations': [], 'trafficAllocation': [], - 'audienceIds': [], - 'includedFlags': [multi_variate_feature_id], - 'excludedFlags': [] + 'audienceIds': [] }, { 'id': 'holdout_3', @@ -1415,9 +1407,7 @@ def setUp(self): 'status': 'Inactive', 'variations': [], 'trafficAllocation': [], - 'audienceIds': [], - 'includedFlags': [boolean_feature_id], - 'excludedFlags': [] + 'audienceIds': [] } ] @@ -1425,55 +1415,6 @@ def setUp(self): opt_obj = optimizely.Optimizely(self.config_json_with_holdouts) self.config_with_holdouts = opt_obj.config_manager.get_config() - def test_get_holdouts_for_flag__non_existent_flag(self): - """ Test that get_holdouts_for_flag returns empty array for non-existent flag. """ - - holdouts = self.config_with_holdouts.get_holdouts_for_flag('non_existent_flag') - self.assertEqual([], holdouts) - - def test_get_holdouts_for_flag__returns_global_and_specific_holdouts(self): - """ Test that get_holdouts_for_flag returns global holdouts that do not exclude the flag - and specific holdouts that include the flag. """ - - holdouts = self.config_with_holdouts.get_holdouts_for_flag('test_feature_in_experiment_and_rollout') - self.assertEqual(2, len(holdouts)) - - global_holdout = next((h for h in holdouts if h['key'] == 'global_holdout'), None) - self.assertIsNotNone(global_holdout) - self.assertEqual('holdout_1', global_holdout['id']) - - specific_holdout = next((h for h in holdouts if h['key'] == 'specific_holdout'), None) - self.assertIsNotNone(specific_holdout) - self.assertEqual('holdout_2', specific_holdout['id']) - - def test_get_holdouts_for_flag__excludes_global_holdouts_for_excluded_flags(self): - """ Test that get_holdouts_for_flag does not return global holdouts that exclude the flag. """ - - holdouts = self.config_with_holdouts.get_holdouts_for_flag('boolean_single_variable_feature') - self.assertEqual(0, len(holdouts)) - - global_holdout = next((h for h in holdouts if h['key'] == 'global_holdout'), None) - self.assertIsNone(global_holdout) - - def test_get_holdouts_for_flag__caches_results(self): - """ Test that get_holdouts_for_flag caches results for subsequent calls. """ - - holdouts1 = self.config_with_holdouts.get_holdouts_for_flag('test_feature_in_experiment_and_rollout') - holdouts2 = self.config_with_holdouts.get_holdouts_for_flag('test_feature_in_experiment_and_rollout') - - # Should be the same object (cached) - self.assertIs(holdouts1, holdouts2) - self.assertEqual(2, len(holdouts1)) - - def test_get_holdouts_for_flag__returns_only_global_for_non_targeted_flags(self): - """ Test that get_holdouts_for_flag returns only global holdouts for flags not specifically targeted. """ - - holdouts = self.config_with_holdouts.get_holdouts_for_flag('test_feature_in_rollout') - - # Should only include global holdout (not excluded and no specific targeting) - self.assertEqual(1, len(holdouts)) - self.assertEqual('global_holdout', holdouts[0]['key']) - def test_get_holdout__returns_holdout_for_valid_id(self): """ Test that get_holdout returns holdout when valid ID is provided. """ @@ -1516,36 +1457,6 @@ def test_get_holdout__does_not_log_when_found(self): self.assertIsNotNone(result) mock_logger.error.assert_not_called() - def test_holdout_initialization__categorizes_holdouts_properly(self): - """ Test that holdouts are properly categorized during initialization. """ - - self.assertIn('holdout_1', self.config_with_holdouts.holdout_id_map) - self.assertIn('holdout_2', self.config_with_holdouts.holdout_id_map) - # Check if a holdout with ID 'holdout_1' exists in global_holdouts - holdout_ids_in_global = [h.id for h in self.config_with_holdouts.global_holdouts] - self.assertIn('holdout_1', holdout_ids_in_global) - - # Use correct feature flag IDs - boolean_feature_id = '91111' - multi_variate_feature_id = '91114' - - self.assertIn(multi_variate_feature_id, self.config_with_holdouts.included_holdouts) - self.assertTrue(len(self.config_with_holdouts.included_holdouts[multi_variate_feature_id]) > 0) - self.assertNotIn(boolean_feature_id, self.config_with_holdouts.included_holdouts) - - self.assertIn(boolean_feature_id, self.config_with_holdouts.excluded_holdouts) - self.assertTrue(len(self.config_with_holdouts.excluded_holdouts[boolean_feature_id]) > 0) - - def test_holdout_initialization__only_processes_running_holdouts(self): - """ Test that only running holdouts are processed during initialization. """ - - self.assertNotIn('holdout_3', self.config_with_holdouts.holdout_id_map) - self.assertNotIn('holdout_3', self.config_with_holdouts.global_holdouts) - - boolean_feature_id = '91111' - included_for_boolean = self.config_with_holdouts.included_holdouts.get(boolean_feature_id) - self.assertIsNone(included_for_boolean) - class FeatureRolloutConfigTest(base.BaseTest): """Tests for Feature Rollout support in ProjectConfig parsing.""" diff --git a/tests/test_decision_service_holdout.py b/tests/test_decision_service_holdout.py index e286ba5ca..b5584a379 100644 --- a/tests/test_decision_service_holdout.py +++ b/tests/test_decision_service_holdout.py @@ -38,16 +38,11 @@ def setUp(self): # Create a config dict with holdouts and feature flags config_dict_with_holdouts = self.config_dict_with_features.copy() - # Get feature flag ID for test_feature_in_experiment - test_feature_id = '91111' - config_dict_with_holdouts['holdouts'] = [ { 'id': 'holdout_1', 'key': 'test_holdout', 'status': 'Running', - 'includedFlags': [], - 'excludedFlags': [], 'audienceIds': [], 'variations': [ { @@ -76,8 +71,6 @@ def setUp(self): 'id': 'holdout_2', 'key': 'excluded_holdout', 'status': 'Running', - 'includedFlags': [], - 'excludedFlags': [test_feature_id], 'audienceIds': [], 'variations': [ { @@ -268,60 +261,6 @@ def test_holdout_populates_decision_reasons(self): # get_variation_for_feature with holdouts tests - def test_user_bucketed_into_holdout_returns_before_experiments(self): - """ - When user is bucketed into holdout, should return holdout decision - before checking experiments or rollouts. - """ - feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') - self.assertIsNotNone(feature_flag) - - user_context = self.opt_obj.create_user_context('testUserId', {}) - - # Mock get_holdouts_for_flag to return holdouts - holdout = self.config_with_holdouts.holdouts[0] if self.config_with_holdouts.holdouts else None - self.assertIsNotNone(holdout) - - holdout_variation = holdout.variations[0] - - # Create a holdout decision - mock_holdout_decision = decision_service.Decision( - experiment=holdout, - variation=holdout_variation, - source=enums.DecisionSources.HOLDOUT, - cmab_uuid=None - ) - - mock_holdout_result = { - 'decision': mock_holdout_decision, - 'error': False, - 'reasons': [] - } - - # Mock get_holdouts_for_flag to return holdouts so the holdout path is taken - with mock.patch.object( - self.config_with_holdouts, - 'get_holdouts_for_flag', - return_value=[holdout] - ): - with mock.patch.object( - self.opt_obj.decision_service, - 'get_variation_for_holdout', - return_value=mock_holdout_result - ): - decision_result = self.opt_obj.decision_service.get_variation_for_feature( - self.config_with_holdouts, - feature_flag, - user_context - ) - - self.assertIsNotNone(decision_result) - - # Decision should be valid and from holdout - decision = decision_result['decision'] - self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) - self.assertIsNotNone(decision.variation) - def test_no_holdout_decision_falls_through_to_experiment_and_rollout(self): """When holdout returns no decision, should fall through to experiment and rollout evaluation.""" feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') @@ -376,42 +315,6 @@ def test_evaluates_holdouts_before_experiments(self): self.assertIsNotNone(decision_result) - def test_evaluates_global_holdouts_for_all_flags(self): - """Should evaluate global holdouts for all flags.""" - feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') - self.assertIsNotNone(feature_flag) - - # Get global holdouts - global_holdouts = [ - h for h in self.config_with_holdouts.holdouts - if not h.includedFlags or len(h.includedFlags) == 0 - ] - - if global_holdouts: - user_context = self.opt_obj.create_user_context('testUserId', {}) - - result = self.decision_service_with_holdouts.get_variations_for_feature_list( - self.config_with_holdouts, - [feature_flag], - user_context, - [] - ) - - self.assertIsNotNone(result) - self.assertIsInstance(result, list) - - def test_respects_included_and_excluded_flags_configuration(self): - """Should respect included and excluded flags configuration.""" - feature_flag = self.config_with_holdouts.get_feature_from_key('test_feature_in_experiment') - - if feature_flag: - # Get holdouts for this flag - holdouts_for_flag = self.config_with_holdouts.get_holdouts_for_flag('test_feature_in_experiment') - - # Should not include holdouts that exclude this flag - excluded_holdout = next((h for h in holdouts_for_flag if h.key == 'excluded_holdout'), None) - self.assertIsNone(excluded_holdout) - # Holdout logging and error handling tests def test_logs_when_holdout_evaluation_starts(self): @@ -618,8 +521,6 @@ def test_decide_with_holdout_sends_impression_event(self): 'id': 'holdout_1', 'key': 'test_holdout', 'status': 'Running', - 'includedFlags': [], - 'excludedFlags': [], 'audienceIds': [], 'variations': [ { @@ -727,8 +628,6 @@ def test_decide_with_holdout_does_not_send_impression_when_disabled(self): 'id': 'holdout_1', 'key': 'test_holdout', 'status': 'Running', - 'includedFlags': [], - 'excludedFlags': [], 'audienceIds': [], 'variations': [ { @@ -801,8 +700,6 @@ def notification_callback(notification_type, user_id, user_attributes, decision_ 'id': 'holdout_1', 'key': 'test_holdout', 'status': 'Running', - 'includedFlags': [], - 'excludedFlags': [], 'audienceIds': [], 'variations': [ { @@ -930,8 +827,6 @@ def test_decide_all_with_global_holdout(self): 'id': 'global_holdout', 'key': 'global_test_holdout', 'status': 'Running', - 'includedFlags': [], # Global - applies to all flags - 'excludedFlags': [], 'audienceIds': [], 'variations': [ { @@ -968,17 +863,12 @@ def test_decide_all_with_global_holdout(self): def test_decide_all_with_included_flags(self): """Should apply holdout only to included flags in decide_all.""" - # Get feature flag IDs - feature1_id = '91111' # test_feature_in_experiment - config_dict_with_holdouts = self.config_dict_with_features.copy() config_dict_with_holdouts['holdouts'] = [ { 'id': 'included_holdout', 'key': 'specific_holdout', 'status': 'Running', - 'includedFlags': [feature1_id], # Only applies to feature1 - 'excludedFlags': [], 'audienceIds': [], 'variations': [ { @@ -1014,16 +904,12 @@ def test_decide_all_with_included_flags(self): def test_decide_all_with_excluded_flags(self): """Should exclude holdout from excluded flags in decide_all.""" - feature1_id = '91111' # test_feature_in_experiment - config_dict_with_holdouts = self.config_dict_with_features.copy() config_dict_with_holdouts['holdouts'] = [ { 'id': 'excluded_holdout', 'key': 'global_except_one', 'status': 'Running', - 'includedFlags': [], # Global - 'excludedFlags': [feature1_id], # Except feature1 'audienceIds': [], 'variations': [ { @@ -1058,9 +944,6 @@ def test_decide_all_with_excluded_flags(self): def test_decide_all_with_multiple_holdouts(self): """Should handle multiple holdouts with correct priority.""" - feature1_id = '91111' - feature2_id = '91112' - config_dict_with_holdouts = self.config_dict_with_features.copy() config_dict_with_holdouts['holdouts'] = [ # Global holdout (applies to all) @@ -1068,8 +951,6 @@ def test_decide_all_with_multiple_holdouts(self): 'id': 'global_holdout', 'key': 'global_holdout', 'status': 'Running', - 'includedFlags': [], - 'excludedFlags': [], 'audienceIds': [], 'variations': [ { @@ -1091,8 +972,6 @@ def test_decide_all_with_multiple_holdouts(self): 'id': 'specific_holdout', 'key': 'specific_holdout', 'status': 'Running', - 'includedFlags': [feature2_id], - 'excludedFlags': [], 'audienceIds': [], 'variations': [ { @@ -1114,8 +993,6 @@ def test_decide_all_with_multiple_holdouts(self): 'id': 'excluded_holdout', 'key': 'excluded_holdout', 'status': 'Running', - 'includedFlags': [], - 'excludedFlags': [feature1_id], 'audienceIds': [], 'variations': [ { @@ -1154,8 +1031,6 @@ def test_decide_all_with_enabled_flags_only_option(self): 'id': 'disabled_holdout', 'key': 'disabled_holdout', 'status': 'Running', - 'includedFlags': [], - 'excludedFlags': [], 'audienceIds': [], 'variations': [ { @@ -1203,8 +1078,6 @@ def test_holdout_impression_event_has_correct_metadata(self): 'id': 'metadata_holdout', 'key': 'metadata_test_holdout', 'status': 'Running', - 'includedFlags': [], - 'excludedFlags': [], 'audienceIds': [], 'variations': [ { @@ -1257,8 +1130,6 @@ def test_holdout_impression_respects_send_flag_decisions_false(self): 'id': 'send_flag_holdout', 'key': 'send_flag_test_holdout', 'status': 'Running', - 'includedFlags': [], - 'excludedFlags': [], 'audienceIds': [], 'variations': [ { @@ -1307,8 +1178,6 @@ def test_holdout_not_running_does_not_apply(self): 'id': 'draft_holdout', 'key': 'draft_holdout', 'status': 'Draft', # Not Running - 'includedFlags': [], - 'excludedFlags': [], 'audienceIds': [], 'variations': [ { @@ -1347,8 +1216,6 @@ def test_holdout_concluded_status_does_not_apply(self): 'id': 'concluded_holdout', 'key': 'concluded_holdout', 'status': 'Concluded', - 'includedFlags': [], - 'excludedFlags': [], 'audienceIds': [], 'variations': [ { @@ -1387,8 +1254,6 @@ def test_holdout_archived_status_does_not_apply(self): 'id': 'archived_holdout', 'key': 'archived_holdout', 'status': 'Archived', - 'includedFlags': [], - 'excludedFlags': [], 'audienceIds': [], 'variations': [ { @@ -1431,8 +1296,6 @@ def test_holdout_with_audience_match(self): 'id': 'audience_holdout', 'key': 'audience_test_holdout', 'status': 'Running', - 'includedFlags': [], - 'excludedFlags': [], 'audienceIds': ['11154'], # Requires browser_type=chrome 'variations': [ { From 807d75b10fbe71bad9dc75c002a0fd222a6cc956 Mon Sep 17 00:00:00 2001 From: Farhan Anjum Date: Thu, 30 Apr 2026 17:38:08 +0600 Subject: [PATCH 19/32] [FSSDK-12521] chore: preparing for release v5.5.0 (#508) * [FSSDK-12521] chore: preparing for release v5.5.0 Co-Authored-By: Claude Opus 4.6 (1M context) * chore: remove internal tooling entries from changelog Removed ruff linter migration and Arnica code risk warning entries from the v5.5.0 changelog as they are internal CI/tooling changes not relevant to SDK users. Co-Authored-By: Claude Opus 4.6 (1M context) * Update CHANGELOG.md Co-authored-by: Muzahidul Islam <129880873+muzahidul-opti@users.noreply.github.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) Co-authored-by: Muzahidul Islam <129880873+muzahidul-opti@users.noreply.github.com> --- CHANGELOG.md | 28 ++++++++++++++++++++++++++++ optimizely/version.py | 2 +- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f5091a0e7..715ee3910 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,33 @@ # Optimizely Python SDK Changelog +## 5.5.0 +April 30th, 2026 + +### New Features + +#### **Feature Rollout Support** + +- Added support for Feature Rollouts, a new rule type that combines Targeted Delivery simplicity with A/B test measurement capabilities. During project config parsing, the "everyone else" variation from the flag's rollout is automatically injected into feature rollout experiments, enabling correct evaluation without changes to decision logic. ([#499](https://github.com/optimizely/python-sdk/pull/499)) +- Removed experiment type validation from config parsing to support flexible rule types. ([#500](https://github.com/optimizely/python-sdk/pull/500)) + +--- + +### Enhancements + +- Added event retry support for reliable event dispatching. ([#475](https://github.com/optimizely/python-sdk/pull/475)) +- Excluded CMAB experiments from UserProfileService to prevent stale cached decisions. ([#474](https://github.com/optimizely/python-sdk/pull/474)) +- Cleaned up flag-level holdout fields for simplified configuration. ([#507](https://github.com/optimizely/python-sdk/pull/507)) + +--- + +### Bug Fixes + +- Fixed `return` in `finally` block silently swallowing exceptions. ([#505](https://github.com/optimizely/python-sdk/pull/505)) +- Fixed `PollingConfigManager` rejecting valid URL-only configuration. ([#497](https://github.com/optimizely/python-sdk/pull/497)) + +--- + + ## 5.4.0 December 19th, 2025 diff --git a/optimizely/version.py b/optimizely/version.py index aef5b3670..85bb307e6 100644 --- a/optimizely/version.py +++ b/optimizely/version.py @@ -11,5 +11,5 @@ # See the License for the specific language governing permissions and # limitations under the License. -version_info = (5, 4, 0) +version_info = (5, 5, 0) __version__ = '.'.join(str(v) for v in version_info) From 013ddf06e9e9bf0f3946908aa5a7c0e2294a9c85 Mon Sep 17 00:00:00 2001 From: Matjaz Pirnovar Date: Mon, 1 Jun 2026 09:03:46 -0700 Subject: [PATCH 20/32] [AI-FSSDK] [FSSDK-12369] Add local holdouts support to Python SDK (#512) * [AI-FSSDK] [FSSDK-12369] Add local holdouts support to Python SDK * [FSSDK-12369] Fix copyright year from 2025 to 2026 in new test files Co-Authored-By: Claude Sonnet 4.6 * [FSSDK-12369] Add mandatory forced-decision-beats-local-holdout enforcement test * trigger CI * trigger CI Co-Authored-By: Claude Opus 4.6 (1M context) --------- Co-authored-by: Claude Sonnet 4.6 Co-authored-by: Farhan Anjum --- optimizely/decision_service.py | 48 +++- optimizely/entities.py | 15 ++ optimizely/helpers/types.py | 1 + optimizely/project_config.py | 47 +++- tests/test_decision_service_holdout.py | 355 ++++++++++++++++++++++++- tests/test_holdout_config.py | 312 ++++++++++++++++++++++ 6 files changed, 759 insertions(+), 19 deletions(-) create mode 100644 tests/test_holdout_config.py diff --git a/optimizely/decision_service.py b/optimizely/decision_service.py index be2be2c54..111889084 100644 --- a/optimizely/decision_service.py +++ b/optimizely/decision_service.py @@ -610,6 +610,24 @@ def get_variation_for_rollout( return Decision(experiment=rule, variation=forced_decision_variation, source=enums.DecisionSources.ROLLOUT, cmab_uuid=None), decide_reasons + # Check local holdouts targeting this specific delivery rule (FSSDK-12369) + local_holdouts = project_config.get_holdouts_for_rule(rule.id) + for holdout in local_holdouts: + local_holdout_decision = self.get_variation_for_holdout( + holdout, user_context, project_config + ) + decide_reasons.extend(local_holdout_decision['reasons']) + + local_decision = local_holdout_decision['decision'] + if local_decision.variation is not None: + message = ( + f"The user '{user_id}' is bucketed into local holdout '{holdout.key}' " + f"for delivery rule '{rule.key}'." + ) + self.logger.info(message) + decide_reasons.append(message) + return local_decision, decide_reasons + bucketing_id, bucket_reasons = self._get_bucketing_id(user_id, attributes) decide_reasons += bucket_reasons @@ -733,9 +751,9 @@ def get_decision_for_flag( reasons = decide_reasons.copy() if decide_reasons else [] user_id = user_context.user_id - # Check holdouts - holdouts = project_config.get_holdouts_for_flag(feature_flag.key) - for holdout in holdouts: + # Check global holdouts (flag level — before any rules are evaluated) + global_holdouts = project_config.get_global_holdouts() + for holdout in global_holdouts: holdout_decision = self.get_variation_for_holdout(holdout, user_context, project_config) reasons.extend(holdout_decision['reasons']) @@ -756,7 +774,7 @@ def get_decision_for_flag( 'reasons': reasons } - # If no holdout decision, check experiments then rollouts + # If no global holdout decision, check experiments then rollouts if feature_flag.experimentIds: for experiment_id in feature_flag.experimentIds: experiment = project_config.get_experiment_from_id(experiment_id) @@ -778,6 +796,28 @@ def get_decision_for_flag( 'reasons': reasons } + # Check local holdouts targeting this specific experiment rule (FSSDK-12369) + local_holdouts = project_config.get_holdouts_for_rule(experiment.id) + for holdout in local_holdouts: + local_holdout_decision = self.get_variation_for_holdout( + holdout, user_context, project_config + ) + reasons.extend(local_holdout_decision['reasons']) + + local_decision = local_holdout_decision['decision'] + if local_decision.variation is not None: + message = ( + f"The user '{user_id}' is bucketed into local holdout '{holdout.key}' " + f"for experiment rule '{experiment.key}'." + ) + self.logger.info(message) + reasons.append(message) + return { + 'decision': local_holdout_decision['decision'], + 'error': False, + 'reasons': reasons + } + # Get variation for experiment variation_result = self.get_variation( project_config, experiment, user_context, user_profile_tracker, reasons, decide_options diff --git a/optimizely/entities.py b/optimizely/entities.py index f67dee893..e15595b45 100644 --- a/optimizely/entities.py +++ b/optimizely/entities.py @@ -223,6 +223,7 @@ def __init__( trafficAllocation: list[TrafficAllocation], audienceIds: list[str], audienceConditions: Optional[Sequence[str | list[str]]] = None, + includedRules: Optional[list[str]] = None, **kwargs: Any ): self.id = id @@ -232,6 +233,8 @@ def __init__( self.trafficAllocation = trafficAllocation self.audienceIds = audienceIds self.audienceConditions = audienceConditions + # None = global holdout (applies to all rules); list of rule IDs = local holdout + self.included_rules: Optional[list[str]] = includedRules def get_audience_conditions_or_ids(self) -> Sequence[str | list[str]]: """Returns audienceConditions if present, otherwise audienceIds. @@ -241,6 +244,18 @@ def get_audience_conditions_or_ids(self) -> Sequence[str | list[str]]: """ return self.audienceConditions if self.audienceConditions is not None else self.audienceIds + @property + def is_global(self) -> bool: + """Check if this is a global holdout (applies to all rules across all flags). + + A holdout is global when includedRules is None (absent from datafile). + An empty list [] is a local holdout that targets no rules (different from global). + + Returns: + True if included_rules is None (global), False otherwise (local). + """ + return self.included_rules is None + @property def is_activated(self) -> bool: """Check if the holdout is activated (running). diff --git a/optimizely/helpers/types.py b/optimizely/helpers/types.py index 6b704c363..7ee51373b 100644 --- a/optimizely/helpers/types.py +++ b/optimizely/helpers/types.py @@ -130,3 +130,4 @@ class HoldoutDict(ExperimentDict): Extends ExperimentDict with holdout-specific properties. """ holdoutStatus: HoldoutStatus + includedRules: Optional[list[str]] # None = global holdout; list of rule IDs = local holdout diff --git a/optimizely/project_config.py b/optimizely/project_config.py index 0fb0f35f1..5ec5f85bf 100644 --- a/optimizely/project_config.py +++ b/optimizely/project_config.py @@ -93,7 +93,10 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): holdouts_data: list[types.HoldoutDict] = config.get('holdouts', []) self.holdouts: list[entities.Holdout] = [] self.holdout_id_map: dict[str, entities.Holdout] = {} - self.flag_holdouts_map: dict[str, list[entities.Holdout]] = {} + # Global holdouts (includedRules is None) — evaluated at flag level before any rule + self.global_holdouts: list[entities.Holdout] = [] + # Rule-level holdouts — map from rule ID to holdouts targeting that rule + self.rule_holdouts_map: dict[str, list[entities.Holdout]] = {} # Convert holdout dicts to Holdout entities for holdout_data in holdouts_data: @@ -108,6 +111,16 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): # Map by ID for quick lookup self.holdout_id_map[holdout.id] = holdout + # Classify holdout as global or local based on includedRules + if holdout.is_global: + self.global_holdouts.append(holdout) + else: + # Local holdout — register for each targeted rule ID + for rule_id in (holdout.included_rules or []): + if rule_id not in self.rule_holdouts_map: + self.rule_holdouts_map[rule_id] = [] + self.rule_holdouts_map[rule_id].append(holdout) + # Utility maps for quick lookup self.group_id_map: dict[str, entities.Group] = self._generate_key_map(self.groups, 'id', entities.Group) self.experiment_id_map: dict[str, entities.Experiment] = self._generate_key_map( @@ -240,11 +253,6 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): everyone_else_variation.variables, 'id', entities.Variation.VariableUsage ) - # Map all running holdouts to this flag - applicable_holdouts = list(self.holdout_id_map.values()) - if applicable_holdouts: - self.flag_holdouts_map[feature.key] = applicable_holdouts - rollout = None if len(feature.rolloutId) == 0 else self.rollout_id_map[feature.rolloutId] if rollout: for exp in rollout.experiments: @@ -878,19 +886,30 @@ def get_flag_variation( return None - def get_holdouts_for_flag(self, flag_key: str) -> list[entities.Holdout]: - """ Helper method to get holdouts from an applied feature flag. + def get_global_holdouts(self) -> list[entities.Holdout]: + """Return all global holdouts (includedRules is None). - Args: - flag_key: Key of the feature flag. + Global holdouts are evaluated at flag level before any rule is checked. Returns: - The holdouts that apply for a specific flag as Holdout entity objects. + List of global Holdout entities that are currently running. """ - if not self.holdouts: - return [] + return self.global_holdouts + + def get_holdouts_for_rule(self, rule_id: str) -> list[entities.Holdout]: + """Return local holdouts that target a specific rule. - return self.flag_holdouts_map.get(flag_key, []) + Local holdouts are evaluated per-rule, before the rule's audience and + traffic allocation checks. A rule ID not present in any holdout's + includedRules simply returns an empty list — silently skipped. + + Args: + rule_id: The experiment or delivery rule ID to look up. + + Returns: + List of local Holdout entities targeting the given rule ID. + """ + return self.rule_holdouts_map.get(rule_id, []) def get_holdout(self, holdout_id: str) -> Optional[entities.Holdout]: """ Helper method to get holdout from holdout ID. diff --git a/tests/test_decision_service_holdout.py b/tests/test_decision_service_holdout.py index b5584a379..1bf81c937 100644 --- a/tests/test_decision_service_holdout.py +++ b/tests/test_decision_service_holdout.py @@ -1,4 +1,4 @@ -# Copyright 2025 Optimizely and contributors +# Copyright 2026 Optimizely and contributors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -1331,3 +1331,356 @@ def test_holdout_with_audience_match(self): self.assertIsNotNone(decision_no_match) finally: opt.close() + + +# --------------------------------------------------------------------------- +# Level 2: Local Holdouts Decision Service Tests (FSSDK-12369) +# --------------------------------------------------------------------------- + +_HOLDOUT_VARIATION = [{'id': 'hvar_1', 'key': 'holdout_control', 'variables': []}] +_FULL_TRAFFIC = [{'entityId': 'hvar_1', 'endOfRange': 10000}] +_NO_TRAFFIC = [{'entityId': 'hvar_1', 'endOfRange': 0}] + + +def _holdout(holdout_id, key, included_rules=None, traffic=None, status='Running'): + """Build a minimal holdout datafile dict.""" + h = { + 'id': holdout_id, + 'key': key, + 'status': status, + 'audienceIds': [], + 'variations': _HOLDOUT_VARIATION, + 'trafficAllocation': traffic or _FULL_TRAFFIC, + } + if included_rules is not None: + h['includedRules'] = included_rules + return h + + +class LocalHoldoutDecisionServiceTest(base.BaseTest): + """Level 2 decision service tests for local holdouts (FSSDK-12369). + + These tests exercise the decision flow branches introduced by local holdouts + and must live in the decision service test file per [UNITTEST] spec. + + Experiment '111127' is the experiment rule for feature 'test_feature_in_experiment'. + Rollout '211111' with rule '211147' (no audience, 60% traffic) is the delivery rule + for 'test_feature_in_rollout'. + """ + + def setUp(self): + base.BaseTest.setUp(self) + self.error_handler = error_handler.NoOpErrorHandler() + self.spy_logger = mock.MagicMock(spec=logger.SimpleLogger) + self.spy_logger.logger = self.spy_logger + self.spy_user_profile_service = mock.MagicMock() + self.spy_cmab_service = mock.MagicMock() + + def tearDown(self): + if hasattr(self, 'opt_obj'): + self.opt_obj.close() + + def _make_opt(self, holdouts): + cfg = self.config_dict_with_features.copy() + cfg['holdouts'] = holdouts + self.opt_obj = optimizely_module.Optimizely(json.dumps(cfg)) + return self.opt_obj + + def _decision_svc(self): + return decision_service.DecisionService( + self.spy_logger, + self.spy_user_profile_service, + self.spy_cmab_service, + ) + + # ------------------------------------------------------------------ + # Branch 1: Global holdout evaluated at flag level + # ------------------------------------------------------------------ + + def test_global_holdout_evaluated_before_any_rule(self): + """User in a global holdout returns holdout decision before any rule is evaluated. + + The global holdout has full traffic allocation and no audience restriction, + so the user must be caught at flag level before experiments are checked. + """ + opt = self._make_opt([_holdout('gh1', 'global_full', traffic=_FULL_TRAFFIC)]) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + ds = self._decision_svc() + + # Mock get_variation so we can assert it was NOT called (holdout short-circuits) + with mock.patch.object(ds, 'get_variation', wraps=ds.get_variation) as mock_get_variation: + user_ctx = opt.create_user_context('user_in_global_holdout', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + decision = result['decision'] + self.assertIsNotNone(decision) + # Source must be HOLDOUT + self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) + # Experiment-level get_variation should not have been called + mock_get_variation.assert_not_called() + + def test_global_holdout_miss_falls_through_to_experiment(self): + """User not in the global holdout falls through to experiment evaluation.""" + # Zero-traffic global holdout — nobody bucketed in + opt = self._make_opt([_holdout('gh1', 'global_zero', traffic=_NO_TRAFFIC)]) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + ds = self._decision_svc() + user_ctx = opt.create_user_context('testUserId', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + self.assertIsNotNone(result) + # Source must NOT be HOLDOUT — user fell through to experiment or rollout + decision = result['decision'] + self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) + + # ------------------------------------------------------------------ + # Branch 2: Local holdout hit — user bucketed into local holdout for rule X + # ------------------------------------------------------------------ + + def test_local_holdout_hit_returns_holdout_decision_for_experiment_rule(self): + """User bucketed into local holdout for experiment rule X returns holdout decision. + + The experiment rule ID is '111127' (test_experiment linked to test_feature_in_experiment). + The local holdout targets only this rule with full traffic. + Audience and traffic allocation for the experiment itself must NOT be evaluated. + """ + experiment_rule_id = '111127' + opt = self._make_opt([ + _holdout('lh1', 'local_for_exp', included_rules=[experiment_rule_id], traffic=_FULL_TRAFFIC) + ]) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + ds = self._decision_svc() + + with mock.patch.object(ds, 'get_variation', wraps=ds.get_variation) as mock_get_var: + user_ctx = opt.create_user_context('user_in_local_holdout', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + decision = result['decision'] + # User must be caught by local holdout + self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) + # Regular experiment evaluation (get_variation) must not have run + mock_get_var.assert_not_called() + + def test_local_holdout_hit_returns_holdout_decision_for_delivery_rule(self): + """User bucketed into local holdout for delivery/rollout rule returns holdout decision. + + Rule '211147' is the everyone-else rollout rule for 'test_feature_in_rollout'. + The local holdout targets this delivery rule with full traffic. + """ + delivery_rule_id = '211147' + opt = self._make_opt([ + _holdout('lh2', 'local_for_delivery', included_rules=[delivery_rule_id], traffic=_FULL_TRAFFIC) + ]) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_rollout') + self.assertIsNotNone(feature_flag) + + ds = self._decision_svc() + user_ctx = opt.create_user_context('user_delivery_holdout', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + self.assertIsNotNone(result) + decision = result['decision'] + self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) + + # ------------------------------------------------------------------ + # Branch 3: Local holdout miss — user falls through to regular rule evaluation + # ------------------------------------------------------------------ + + def test_local_holdout_miss_falls_through_to_regular_rule_evaluation(self): + """User not bucketed into local holdout falls through to normal experiment evaluation. + + Zero-traffic local holdout — nobody bucketed in — user proceeds to experiment. + """ + experiment_rule_id = '111127' + opt = self._make_opt([ + _holdout('lh_miss', 'local_no_traffic', included_rules=[experiment_rule_id], traffic=_NO_TRAFFIC) + ]) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + ds = self._decision_svc() + user_ctx = opt.create_user_context('testUserId', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + self.assertIsNotNone(result) + decision = result['decision'] + # Source must NOT be HOLDOUT — missed the local holdout + self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) + + # ------------------------------------------------------------------ + # Branch 4: Rule specificity — local holdout for rule X does NOT affect rule Y + # ------------------------------------------------------------------ + + def test_local_holdout_for_rule_x_does_not_affect_rule_y(self): + """Local holdout targeting experiment rule '111127' must not apply to rollout rule '211147'. + + get_holdouts_for_rule('211147') should return empty — the holdout only targets '111127'. + """ + experiment_rule_id = '111127' + delivery_rule_id = '211147' + + opt = self._make_opt([ + _holdout('lh_x', 'local_for_exp_only', included_rules=[experiment_rule_id], traffic=_FULL_TRAFFIC) + ]) + config = opt.config_manager.get_config() + + # Verify rule map specificity via project config API + holdouts_for_exp = config.get_holdouts_for_rule(experiment_rule_id) + holdouts_for_delivery = config.get_holdouts_for_rule(delivery_rule_id) + + self.assertEqual(len(holdouts_for_exp), 1) + self.assertEqual(holdouts_for_exp[0].id, 'lh_x') + self.assertEqual(holdouts_for_delivery, []) + + def test_two_rules_each_with_own_local_holdout_are_independent(self): + """Each rule's local holdout evaluation is independent of other rules.""" + exp_rule_id = '111127' + delivery_rule_id = '211147' + + opt = self._make_opt([ + _holdout('lh_exp', 'for_exp', included_rules=[exp_rule_id], traffic=_FULL_TRAFFIC), + _holdout('lh_del', 'for_del', included_rules=[delivery_rule_id], traffic=_FULL_TRAFFIC), + ]) + config = opt.config_manager.get_config() + + exp_holdouts = config.get_holdouts_for_rule(exp_rule_id) + del_holdouts = config.get_holdouts_for_rule(delivery_rule_id) + + exp_ids = {h.id for h in exp_holdouts} + del_ids = {h.id for h in del_holdouts} + + self.assertIn('lh_exp', exp_ids) + self.assertNotIn('lh_del', exp_ids) + + self.assertIn('lh_del', del_ids) + self.assertNotIn('lh_exp', del_ids) + + # ------------------------------------------------------------------ + # Branch 5: Experiment vs delivery rules — local holdout applies to both + # ------------------------------------------------------------------ + + def test_local_holdout_applies_to_experiment_rule(self): + """Local holdout check applies to experiment rules in get_decision_for_flag.""" + experiment_rule_id = '111127' + opt = self._make_opt([ + _holdout('lh_exp', 'for_experiment', included_rules=[experiment_rule_id], traffic=_FULL_TRAFFIC) + ]) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + + ds = self._decision_svc() + user_ctx = opt.create_user_context('user_exp_holdout', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + self.assertEqual(result['decision'].source, enums.DecisionSources.HOLDOUT) + + def test_local_holdout_applies_to_rollout_delivery_rule(self): + """Local holdout check applies to rollout/delivery rules in get_decision_for_flag.""" + delivery_rule_id = '211147' + opt = self._make_opt([ + _holdout('lh_del', 'for_delivery', included_rules=[delivery_rule_id], traffic=_FULL_TRAFFIC) + ]) + config = opt.config_manager.get_config() + # test_feature_in_rollout only has rollout rules, no experiment rules + feature_flag = config.get_feature_from_key('test_feature_in_rollout') + self.assertIsNotNone(feature_flag) + + ds = self._decision_svc() + user_ctx = opt.create_user_context('user_delivery_holdout', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + self.assertIsNotNone(result) + decision = result['decision'] + self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) + + # ------------------------------------------------------------------ + # Precedence: Global → Forced → Local → Regular rule + # ------------------------------------------------------------------ + + def test_global_holdout_takes_precedence_over_local_holdout(self): + """Global holdout evaluated first — user caught before local holdout check.""" + experiment_rule_id = '111127' + opt = self._make_opt([ + _holdout('gh1', 'global_full', traffic=_FULL_TRAFFIC), # global, full traffic + _holdout('lh1', 'local_full', included_rules=[experiment_rule_id], traffic=_FULL_TRAFFIC), + ]) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + + ds = self._decision_svc() + + # Mock local holdout evaluation to verify it is never reached + with mock.patch.object(config, 'get_holdouts_for_rule', wraps=config.get_holdouts_for_rule) as mock_local: + user_ctx = opt.create_user_context('user_global_first', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + self.assertEqual(result['decision'].source, enums.DecisionSources.HOLDOUT) + # get_holdouts_for_rule should NOT be called — global holdout short-circuited + mock_local.assert_not_called() + + def test_forced_decision_beats_100_percent_local_holdout(self): + """Forced decision MUST win over a 100% traffic local holdout targeting the same rule. + + MANDATORY ENFORCEMENT TEST (cross-sdk guideline): + Setup: User has a forced decision set for rule 'test_experiment'. A local holdout + targets rule '111127' (same rule) with 100% traffic allocation. + Assert: The forced decision variation is returned — NOT the holdout variation. + If this test fails, the per-rule ordering (forced → local holdout → regular) is wrong. + """ + from optimizely.optimizely_user_context import OptimizelyUserContext + + experiment_rule_id = '111127' # id of 'test_experiment' + forced_variation_key = 'control' # a valid variation key in test_experiment + + opt = self._make_opt([ + _holdout('lh_full', 'local_full_traffic', included_rules=[experiment_rule_id], traffic=_FULL_TRAFFIC) + ]) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + self.assertIsNotNone(feature_flag) + + ds = self._decision_svc() + user_ctx = opt.create_user_context('forced_user', {}) + + # Set forced decision for 'test_feature_in_experiment' with rule 'test_experiment' + decision_context = OptimizelyUserContext.OptimizelyDecisionContext( + flag_key='test_feature_in_experiment', + rule_key='test_experiment' + ) + forced_decision = OptimizelyUserContext.OptimizelyForcedDecision( + variation_key=forced_variation_key + ) + user_ctx.set_forced_decision(decision_context, forced_decision) + + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + decision = result['decision'] + self.assertIsNotNone(decision) + # The forced decision variation must be returned, NOT a holdout variation + self.assertEqual(decision.variation.key, forced_variation_key) + self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) + + def test_no_holdouts_at_all_falls_through_to_experiment(self): + """When there are no holdouts, decision falls through to experiment evaluation.""" + opt = self._make_opt([]) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + + ds = self._decision_svc() + user_ctx = opt.create_user_context('testUserId', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + self.assertIsNotNone(result) + decision = result['decision'] + self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) diff --git a/tests/test_holdout_config.py b/tests/test_holdout_config.py new file mode 100644 index 000000000..3d8cd08c9 --- /dev/null +++ b/tests/test_holdout_config.py @@ -0,0 +1,312 @@ +# Copyright 2026 Optimizely and contributors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Level 1 tests for holdout config parsing and data model (FSSDK-12369). + +Tests cover: +- isGlobal classification (includedRules == None vs list) +- get_global_holdouts() returns only global holdouts +- get_holdouts_for_rule() returns local holdouts for a specific rule +- Backward compatibility with old datafiles (no includedRules field) +- Edge cases: empty array vs None, unknown rule IDs, cross-flag targeting +""" + +import json +import unittest + +from optimizely import entities +from optimizely import optimizely as optimizely_module +from tests import base + + +HOLDOUT_VARIATION = [ + {'id': 'holdout_var_1', 'key': 'holdout_control', 'variables': []} +] + +FULL_TRAFFIC = [{'entityId': 'holdout_var_1', 'endOfRange': 10000}] +NO_TRAFFIC = [{'entityId': 'holdout_var_1', 'endOfRange': 0}] + + +def _make_holdout( + holdout_id: str, + key: str, + included_rules: object = 'MISSING', + status: str = 'Running', +) -> dict: + """Build a holdout datafile dict. Pass included_rules=None for global, + a list for local, or leave as 'MISSING' to omit the field entirely.""" + h: dict = { + 'id': holdout_id, + 'key': key, + 'status': status, + 'audienceIds': [], + 'variations': HOLDOUT_VARIATION, + 'trafficAllocation': FULL_TRAFFIC, + } + if included_rules != 'MISSING': + h['includedRules'] = included_rules + return h + + +def _build_config(holdouts: list, base_test: 'base.BaseTest') -> 'optimizely_module.Optimizely': + """Create an Optimizely instance with the given holdouts list.""" + config_dict = base_test.config_dict_with_features.copy() + config_dict['holdouts'] = holdouts + return optimizely_module.Optimizely(json.dumps(config_dict)) + + +class HoldoutEntityIsGlobalTest(unittest.TestCase): + """Tests for the Holdout.is_global computed property.""" + + def test_is_global_returns_true_when_included_rules_is_none(self): + """Holdout with includedRules=None should be classified as global.""" + holdout = entities.Holdout( + id='h1', key='global_holdout', status='Running', + variations=HOLDOUT_VARIATION, trafficAllocation=FULL_TRAFFIC, + audienceIds=[], includedRules=None + ) + self.assertTrue(holdout.is_global) + + def test_is_global_returns_true_when_included_rules_not_provided(self): + """Holdout with no includedRules kwarg (default None) is global.""" + holdout = entities.Holdout( + id='h1', key='global_holdout', status='Running', + variations=HOLDOUT_VARIATION, trafficAllocation=FULL_TRAFFIC, + audienceIds=[] + ) + self.assertTrue(holdout.is_global) + + def test_is_global_returns_false_when_included_rules_is_empty_list(self): + """Empty list [] is a local holdout targeting no rules — NOT global.""" + holdout = entities.Holdout( + id='h1', key='local_holdout_no_rules', status='Running', + variations=HOLDOUT_VARIATION, trafficAllocation=FULL_TRAFFIC, + audienceIds=[], includedRules=[] + ) + self.assertFalse(holdout.is_global) + + def test_is_global_returns_false_when_included_rules_has_rule_ids(self): + """Holdout with rule IDs is local — is_global should be False.""" + holdout = entities.Holdout( + id='h1', key='local_holdout', status='Running', + variations=HOLDOUT_VARIATION, trafficAllocation=FULL_TRAFFIC, + audienceIds=[], includedRules=['rule_1', 'rule_2'] + ) + self.assertFalse(holdout.is_global) + + def test_included_rules_stored_correctly(self): + """included_rules attribute should match the passed includedRules value.""" + holdout_global = entities.Holdout( + id='h1', key='g', status='Running', + variations=HOLDOUT_VARIATION, trafficAllocation=FULL_TRAFFIC, + audienceIds=[], includedRules=None + ) + holdout_local = entities.Holdout( + id='h2', key='l', status='Running', + variations=HOLDOUT_VARIATION, trafficAllocation=FULL_TRAFFIC, + audienceIds=[], includedRules=['rule_a', 'rule_b'] + ) + self.assertIsNone(holdout_global.included_rules) + self.assertEqual(holdout_local.included_rules, ['rule_a', 'rule_b']) + + +class HoldoutConfigGetGlobalHoldoutsTest(unittest.TestCase): + """Tests for ProjectConfig.get_global_holdouts().""" + + def setUp(self): + base.BaseTest.setUp(self) + + def tearDown(self): + if hasattr(self, 'opt_obj'): + self.opt_obj.close() + + def test_get_global_holdouts_returns_all_global_holdouts(self): + """All holdouts without includedRules should be returned.""" + self.opt_obj = _build_config([ + _make_holdout('h1', 'global_1'), # field absent → global + _make_holdout('h2', 'global_2', None), # explicitly None → global + _make_holdout('h3', 'local_1', ['rule_x']), # local + ], self) + config = self.opt_obj.config_manager.get_config() + global_holdouts = config.get_global_holdouts() + global_ids = {h.id for h in global_holdouts} + self.assertIn('h1', global_ids) + self.assertIn('h2', global_ids) + self.assertNotIn('h3', global_ids) + + def test_get_global_holdouts_returns_empty_when_no_holdouts(self): + """No holdouts in datafile → empty list.""" + self.opt_obj = _build_config([], self) + config = self.opt_obj.config_manager.get_config() + self.assertEqual(config.get_global_holdouts(), []) + + def test_get_global_holdouts_excludes_non_running_holdouts(self): + """Draft holdouts are not activated and should not appear.""" + self.opt_obj = _build_config([ + _make_holdout('h_running', 'running_global', status='Running'), + _make_holdout('h_draft', 'draft_global', status='Draft'), + ], self) + config = self.opt_obj.config_manager.get_config() + global_holdouts = config.get_global_holdouts() + ids = {h.id for h in global_holdouts} + self.assertIn('h_running', ids) + self.assertNotIn('h_draft', ids) + + def test_get_global_holdouts_returns_empty_when_all_local(self): + """If all holdouts are local, global list is empty.""" + self.opt_obj = _build_config([ + _make_holdout('h1', 'local_a', ['rule_1']), + _make_holdout('h2', 'local_b', ['rule_2']), + ], self) + config = self.opt_obj.config_manager.get_config() + self.assertEqual(config.get_global_holdouts(), []) + + +class HoldoutConfigGetHoldoutsForRuleTest(unittest.TestCase): + """Tests for ProjectConfig.get_holdouts_for_rule().""" + + def setUp(self): + base.BaseTest.setUp(self) + + def tearDown(self): + if hasattr(self, 'opt_obj'): + self.opt_obj.close() + + def test_get_holdouts_for_rule_returns_matching_local_holdouts(self): + """Holdout targeting rule_x should be returned for rule_x.""" + self.opt_obj = _build_config([ + _make_holdout('h1', 'local_h', ['rule_x', 'rule_y']), + ], self) + config = self.opt_obj.config_manager.get_config() + holdouts = config.get_holdouts_for_rule('rule_x') + self.assertEqual(len(holdouts), 1) + self.assertEqual(holdouts[0].id, 'h1') + + def test_get_holdouts_for_rule_returns_empty_for_unknown_rule(self): + """Rule ID not found in any holdout's includedRules returns empty list.""" + self.opt_obj = _build_config([ + _make_holdout('h1', 'local_h', ['rule_a']), + ], self) + config = self.opt_obj.config_manager.get_config() + # Silently skip unknown rule IDs + holdouts = config.get_holdouts_for_rule('nonexistent_rule') + self.assertEqual(holdouts, []) + + def test_get_holdouts_for_rule_returns_empty_when_no_holdouts(self): + """No holdouts defined → always returns empty list.""" + self.opt_obj = _build_config([], self) + config = self.opt_obj.config_manager.get_config() + self.assertEqual(config.get_holdouts_for_rule('any_rule'), []) + + def test_get_holdouts_for_rule_multiple_holdouts_for_same_rule(self): + """Multiple holdouts can target the same rule.""" + self.opt_obj = _build_config([ + _make_holdout('h1', 'local_h1', ['rule_x']), + _make_holdout('h2', 'local_h2', ['rule_x', 'rule_y']), + ], self) + config = self.opt_obj.config_manager.get_config() + holdouts = config.get_holdouts_for_rule('rule_x') + ids = {h.id for h in holdouts} + self.assertIn('h1', ids) + self.assertIn('h2', ids) + + def test_get_holdouts_for_rule_does_not_return_global_holdouts(self): + """Global holdouts should not appear in get_holdouts_for_rule results.""" + self.opt_obj = _build_config([ + _make_holdout('global', 'global_holdout'), # field absent → global + _make_holdout('local', 'local_holdout', ['rule_x']), + ], self) + config = self.opt_obj.config_manager.get_config() + holdouts = config.get_holdouts_for_rule('rule_x') + ids = {h.id for h in holdouts} + self.assertNotIn('global', ids) + self.assertIn('local', ids) + + def test_get_holdouts_for_rule_rule_specificity(self): + """A holdout targeting rule_x must not appear for rule_y.""" + self.opt_obj = _build_config([ + _make_holdout('h1', 'local_for_x', ['rule_x']), + ], self) + config = self.opt_obj.config_manager.get_config() + self.assertEqual(config.get_holdouts_for_rule('rule_y'), []) + + def test_get_holdouts_for_rule_cross_flag_targeting(self): + """One holdout can target rules from multiple different flags.""" + self.opt_obj = _build_config([ + _make_holdout('h1', 'cross_flag_holdout', ['rule_flag_a', 'rule_flag_b']), + ], self) + config = self.opt_obj.config_manager.get_config() + for rule_id in ['rule_flag_a', 'rule_flag_b']: + holdouts = config.get_holdouts_for_rule(rule_id) + self.assertEqual(len(holdouts), 1) + self.assertEqual(holdouts[0].id, 'h1') + + +class HoldoutBackwardCompatibilityTest(unittest.TestCase): + """Tests for backward compatibility with old datafiles (no includedRules field).""" + + def setUp(self): + base.BaseTest.setUp(self) + + def tearDown(self): + if hasattr(self, 'opt_obj'): + self.opt_obj.close() + + def test_old_datafile_without_included_rules_treated_as_global(self): + """Datafiles without includedRules field must default to global holdout.""" + # Simulate old datafile — no 'includedRules' key at all + old_holdout = { + 'id': 'old_h', + 'key': 'legacy_holdout', + 'status': 'Running', + 'audienceIds': [], + 'variations': HOLDOUT_VARIATION, + 'trafficAllocation': FULL_TRAFFIC, + } + self.opt_obj = _build_config([old_holdout], self) + config = self.opt_obj.config_manager.get_config() + + global_holdouts = config.get_global_holdouts() + self.assertEqual(len(global_holdouts), 1) + self.assertEqual(global_holdouts[0].id, 'old_h') + self.assertTrue(global_holdouts[0].is_global) + + def test_old_datafile_holdout_does_not_appear_in_rule_map(self): + """Legacy holdouts with no includedRules field must not pollute rule map.""" + old_holdout = { + 'id': 'old_h', + 'key': 'legacy_holdout', + 'status': 'Running', + 'audienceIds': [], + 'variations': HOLDOUT_VARIATION, + 'trafficAllocation': FULL_TRAFFIC, + } + self.opt_obj = _build_config([old_holdout], self) + config = self.opt_obj.config_manager.get_config() + self.assertEqual(config.get_holdouts_for_rule('any_rule'), []) + + def test_empty_included_rules_is_local_not_global(self): + """[] (empty array) is a local holdout targeting no rules — not the same as None.""" + holdout_empty = _make_holdout('h_empty', 'empty_local', included_rules=[]) + holdout_none = _make_holdout('h_none', 'global_none', included_rules=None) + + self.opt_obj = _build_config([holdout_empty, holdout_none], self) + config = self.opt_obj.config_manager.get_config() + + global_holdouts = config.get_global_holdouts() + global_ids = {h.id for h in global_holdouts} + + # None → global; [] → local (does not appear in global list) + self.assertIn('h_none', global_ids) + self.assertNotIn('h_empty', global_ids) From 9bf1c311119967cb07457fb7d6ce4d62ca36db75 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Wed, 3 Jun 2026 09:09:27 -0700 Subject: [PATCH 21/32] [AI-FSSDK] [FSSDK-12670] Block ODP identify event for single identifier (#513) * [AI-FSSDK] [FSSDK-12670] Block ODP identify event for single identifier * [FSSDK-12670] Address review feedback: fix log message * [FSSDK-12670] Retrigger CI * [FSSDK-12670] Add comment explaining the < 2 identifiers guard Co-Authored-By: Claude Opus 4.6 * [FSSDK-12670] retrigger CI --------- Co-authored-by: Claude Opus 4.6 Co-authored-by: Farhan Anjum --- optimizely/odp/odp_event_manager.py | 25 ++++++++++- optimizely/odp/odp_manager.py | 4 +- optimizely/optimizely.py | 4 +- optimizely/optimizely_user_context.py | 4 +- tests/test_odp_manager.py | 60 +++++++++++++++++++++++---- tests/test_optimizely.py | 2 +- tests/test_user_context.py | 4 +- 7 files changed, 86 insertions(+), 17 deletions(-) diff --git a/optimizely/odp/odp_event_manager.py b/optimizely/odp/odp_event_manager.py index 3fb961ac7..a7bd09067 100644 --- a/optimizely/odp/odp_event_manager.py +++ b/optimizely/odp/odp_event_manager.py @@ -267,9 +267,30 @@ def dispatch(self, event: OdpEvent) -> None: except Full: self.logger.warning(Errors.ODP_EVENT_FAILED.format("Queue is full")) - def identify_user(self, user_id: str) -> None: + def identify_user(self, identifiers: dict[str, str]) -> None: + """Send an identify event to ODP if there are multiple valid identifiers. + + An identify event is only useful when there are two or more identifiers + to link together in the ODP user profile. Sending a single identifier + provides no linking value and wastes a network call. + + Args: + identifiers: A dictionary of identifier key-value pairs + (e.g. {"fs_user_id": "abc", "email": "a@b.com"}). + """ + # Filter out identifiers with None or empty string values. + valid_identifiers = {k: v for k, v in identifiers.items() if v} + + # Identify requires 2+ identifiers to link (e.g., vuid + fs_user_id). + # A single identifier has no cross-reference value and generates unnecessary traffic. + if len(valid_identifiers) < 2: + self.logger.debug( + 'ODP identify event is not dispatched (fewer than 2 valid identifiers).' + ) + return + self.send_event(OdpManagerConfig.EVENT_TYPE, 'identified', - {OdpManagerConfig.KEY_FOR_USER_ID: user_id}, {}) + valid_identifiers, {}) def update_config(self) -> None: """Adds update config signal to event_queue.""" diff --git a/optimizely/odp/odp_manager.py b/optimizely/odp/odp_manager.py index a6e262531..10c160e09 100644 --- a/optimizely/odp/odp_manager.py +++ b/optimizely/odp/odp_manager.py @@ -73,7 +73,7 @@ def fetch_qualified_segments(self, user_id: str, options: list[str]) -> Optional return self.segment_manager.fetch_qualified_segments(user_key, user_value, options) - def identify_user(self, user_id: str) -> None: + def identify_user(self, identifiers: dict[str, str]) -> None: if not self.enabled or not self.event_manager: self.logger.debug('ODP identify event is not dispatched (ODP disabled).') return @@ -81,7 +81,7 @@ def identify_user(self, user_id: str) -> None: self.logger.debug('ODP identify event is not dispatched (ODP not integrated).') return - self.event_manager.identify_user(user_id) + self.event_manager.identify_user(identifiers) def send_event(self, type: str, action: str, identifiers: dict[str, str], data: dict[str, Any]) -> None: """ diff --git a/optimizely/optimizely.py b/optimizely/optimizely.py index 4b014e7f2..04162823b 100644 --- a/optimizely/optimizely.py +++ b/optimizely/optimizely.py @@ -1541,7 +1541,7 @@ def _update_odp_config_on_datafile_update(self) -> None: config.all_segments ) - def _identify_user(self, user_id: str) -> None: + def _identify_user(self, identifiers: dict[str, str]) -> None: if not self.is_valid: self.logger.error(enums.Errors.INVALID_OPTIMIZELY.format('identify_user')) return @@ -1551,7 +1551,7 @@ def _identify_user(self, user_id: str) -> None: self.logger.error(enums.Errors.INVALID_PROJECT_CONFIG.format('identify_user')) return - self.odp_manager.identify_user(user_id) + self.odp_manager.identify_user(identifiers) def _fetch_qualified_segments(self, user_id: str, options: Optional[list[str]] = None) -> Optional[list[str]]: if not self.is_valid: diff --git a/optimizely/optimizely_user_context.py b/optimizely/optimizely_user_context.py index e88c0f521..379dfb0ed 100644 --- a/optimizely/optimizely_user_context.py +++ b/optimizely/optimizely_user_context.py @@ -19,6 +19,7 @@ from typing import TYPE_CHECKING, Any, Callable, Optional, NewType, Dict from optimizely.decision import optimizely_decision +from optimizely.helpers.enums import OdpManagerConfig if TYPE_CHECKING: # prevent circular dependency by skipping import at runtime @@ -73,7 +74,8 @@ def __init__( ] = {} if self.client and identify: - self.client._identify_user(user_id) + identifiers = {OdpManagerConfig.KEY_FOR_USER_ID: user_id} + self.client._identify_user(identifiers) class OptimizelyDecisionContext: """ Using class with attributes here instead of namedtuple because diff --git a/tests/test_odp_manager.py b/tests/test_odp_manager.py index ae0e4a1a3..c9483dc0d 100644 --- a/tests/test_odp_manager.py +++ b/tests/test_odp_manager.py @@ -48,7 +48,7 @@ def test_configurations_disable_odp(self): mock_logger.reset_mock() # these call should be dropped gracefully with None - manager.identify_user('user1') + manager.identify_user({'fs_user_id': 'user1'}) manager.send_event('t1', 'a1', {}, {}) mock_logger.error.assert_called_once_with('ODP is not enabled.') @@ -126,10 +126,11 @@ def test_identify_user_datafile_not_ready(self): manager = OdpManager(False, OptimizelySegmentsCache, event_manager=event_manager, logger=mock_logger) + identifiers = {'fs_user_id': 'user1', 'email': 'test@example.com'} with mock.patch.object(event_manager, 'identify_user') as mock_identify_user: - manager.identify_user('user1') + manager.identify_user(identifiers) - mock_identify_user.assert_called_once_with('user1') + mock_identify_user.assert_called_once_with(identifiers) mock_logger.error.assert_not_called() def test_identify_user_odp_integrated(self): @@ -139,13 +140,14 @@ def test_identify_user_odp_integrated(self): manager = OdpManager(False, LRUCache(10, 20), event_manager=event_manager, logger=mock_logger) manager.update_odp_config('key1', 'host1', []) + identifiers = {'fs_user_id': 'user1', 'email': 'test@example.com'} with mock.patch.object(event_manager, 'dispatch') as mock_dispatch_event: - manager.identify_user('user1') + manager.identify_user(identifiers) mock_dispatch_event.assert_called_once_with({ 'type': 'fullstack', 'action': 'identified', - 'identifiers': {'fs_user_id': 'user1'}, + 'identifiers': {'fs_user_id': 'user1', 'email': 'test@example.com'}, 'data': { 'idempotence_id': mock.ANY, 'data_source_type': 'sdk', @@ -161,8 +163,9 @@ def test_identify_user_odp_not_integrated(self): manager = OdpManager(False, CustomCache(), event_manager=event_manager, logger=mock_logger) manager.update_odp_config(None, None, []) + identifiers = {'fs_user_id': 'user1', 'email': 'test@example.com'} with mock.patch.object(event_manager, 'dispatch') as mock_dispatch_event: - manager.identify_user('user1') + manager.identify_user(identifiers) mock_dispatch_event.assert_not_called() mock_logger.error.assert_not_called() @@ -175,13 +178,56 @@ def test_identify_user_odp_disabled(self): manager = OdpManager(False, OptimizelySegmentsCache, event_manager=event_manager, logger=mock_logger) manager.enabled = False + identifiers = {'fs_user_id': 'user1', 'email': 'test@example.com'} with mock.patch.object(event_manager, 'identify_user') as mock_identify_user: - manager.identify_user('user1') + manager.identify_user(identifiers) mock_identify_user.assert_not_called() mock_logger.error.assert_not_called() mock_logger.debug.assert_called_with('ODP identify event is not dispatched (ODP disabled).') + def test_identify_user_single_identifier_skipped(self): + """Identify event should not be sent when only one identifier is provided.""" + mock_logger = mock.MagicMock() + event_manager = OdpEventManager(mock_logger, OdpEventApiManager()) + + manager = OdpManager(False, LRUCache(10, 20), event_manager=event_manager, logger=mock_logger) + manager.update_odp_config('key1', 'host1', []) + + with mock.patch.object(event_manager, 'dispatch') as mock_dispatch_event: + manager.identify_user({'fs_user_id': 'user1'}) + + mock_dispatch_event.assert_not_called() + + def test_identify_user_empty_values_not_counted(self): + """Identifiers with empty or None values should not count toward the minimum.""" + mock_logger = mock.MagicMock() + event_manager = OdpEventManager(mock_logger, OdpEventApiManager()) + + manager = OdpManager(False, LRUCache(10, 20), event_manager=event_manager, logger=mock_logger) + manager.update_odp_config('key1', 'host1', []) + + with mock.patch.object(event_manager, 'dispatch') as mock_dispatch_event: + manager.identify_user({'fs_user_id': 'user1', 'email': '', 'vuid': None}) + + mock_dispatch_event.assert_not_called() + + def test_identify_user_multiple_identifiers_sent(self): + """Identify event should be sent when two or more valid identifiers are provided.""" + mock_logger = mock.MagicMock() + event_manager = OdpEventManager(mock_logger, OdpEventApiManager()) + + manager = OdpManager(False, LRUCache(10, 20), event_manager=event_manager, logger=mock_logger) + manager.update_odp_config('key1', 'host1', []) + + identifiers = {'fs_user_id': 'user1', 'vuid': 'vuid123', 'email': 'a@b.com'} + with mock.patch.object(event_manager, 'dispatch') as mock_dispatch_event: + manager.identify_user(identifiers) + + mock_dispatch_event.assert_called_once() + event = mock_dispatch_event.call_args[0][0] + self.assertEqual(event.identifiers, identifiers) + def test_send_event_datafile_not_ready(self): mock_logger = mock.MagicMock() event_manager = OdpEventManager(mock_logger, OdpEventApiManager()) diff --git a/tests/test_optimizely.py b/tests/test_optimizely.py index c2de186fa..0340ef72a 100644 --- a/tests/test_optimizely.py +++ b/tests/test_optimizely.py @@ -5343,7 +5343,7 @@ def test_send_identify_event__when_called_with_odp_enabled(self): with mock.patch.object(client, '_identify_user') as identify: client.create_user_context('user-id') - identify.assert_called_once_with('user-id') + identify.assert_called_once_with({'fs_user_id': 'user-id'}) mock_logger.error.assert_not_called() client.close() diff --git a/tests/test_user_context.py b/tests/test_user_context.py index 3ae9be0dc..3edb072ce 100644 --- a/tests/test_user_context.py +++ b/tests/test_user_context.py @@ -2094,7 +2094,7 @@ def test_send_identify_event_when_user_context_created(self): with mock.patch.object(client, '_identify_user') as identify: OptimizelyUserContext(client, mock_logger, 'user-id') - identify.assert_called_once_with('user-id') + identify.assert_called_once_with({'fs_user_id': 'user-id'}) mock_logger.error.assert_not_called() client.close() @@ -2104,7 +2104,7 @@ def test_identify_is_skipped_with_decisions(self): with mock.patch.object(client, '_identify_user') as identify: user_context = OptimizelyUserContext(client, mock_logger, 'user-id') - identify.assert_called_once_with('user-id') + identify.assert_called_once_with({'fs_user_id': 'user-id'}) mock_logger.error.assert_not_called() with mock.patch.object(client, '_identify_user') as identify: From a68b31305cbcd2c547ea37174df4873cd0fbdf1c Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Wed, 17 Jun 2026 09:11:38 -0700 Subject: [PATCH 22/32] [AI-FSSDK] [FSSDK-12760] Add localHoldouts datafile section for backward compat (#517) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [AI-FSSDK] [FSSDK-12760] Add localHoldouts datafile section for backward compat * [FSSDK-12760] Clarify holdout scope docs (spec §5 cleanup) Update stale docstrings/comments that described holdout scope as being determined by the includedRules field. After FSSDK-12760, scope is determined by which top-level datafile section the entity is parsed from ('holdouts' = global, 'localHoldouts' = local). The entity-level is_global property continues to compute from included_rules for code holding direct entity references. No behavior change. * [FSSDK-12760] Tighten holdout scope docstrings/comments Condense the spec §5 cleanup comments to one-line/short-docstring form per updated spec guidance. Same content, more compact. * [FSSDK-12760] Empty commit to re-trigger CI * Refactor holdout parsing comments for conciseness * Add warning for ignored 'includedRules' in global holdouts --------- Co-authored-by: Farhan Anjum --- optimizely/entities.py | 13 +- optimizely/helpers/types.py | 4 +- optimizely/project_config.py | 68 +++- tests/test_decision_service_holdout.py | 28 +- tests/test_holdout_config.py | 438 ++++++++++++++++++++++--- 5 files changed, 470 insertions(+), 81 deletions(-) diff --git a/optimizely/entities.py b/optimizely/entities.py index e15595b45..7b0b09e57 100644 --- a/optimizely/entities.py +++ b/optimizely/entities.py @@ -233,7 +233,8 @@ def __init__( self.trafficAllocation = trafficAllocation self.audienceIds = audienceIds self.audienceConditions = audienceConditions - # None = global holdout (applies to all rules); list of rule IDs = local holdout + # Per-rule targeting for local holdouts. Scope comes from the datafile + # section, not this field; ProjectConfig strips it on 'holdouts' entries. self.included_rules: Optional[list[str]] = includedRules def get_audience_conditions_or_ids(self) -> Sequence[str | list[str]]: @@ -246,13 +247,11 @@ def get_audience_conditions_or_ids(self) -> Sequence[str | list[str]]: @property def is_global(self) -> bool: - """Check if this is a global holdout (applies to all rules across all flags). + """True if this is a global holdout. - A holdout is global when includedRules is None (absent from datafile). - An empty list [] is a local holdout that targets no rules (different from global). - - Returns: - True if included_rules is None (global), False otherwise (local). + Scope is set by the datafile section ('holdouts' vs 'localHoldouts'). + ProjectConfig strips 'includedRules' on 'holdouts' entries, so this + property stays consistent with section membership. """ return self.included_rules is None diff --git a/optimizely/helpers/types.py b/optimizely/helpers/types.py index 7ee51373b..7b65ab134 100644 --- a/optimizely/helpers/types.py +++ b/optimizely/helpers/types.py @@ -130,4 +130,6 @@ class HoldoutDict(ExperimentDict): Extends ExperimentDict with holdout-specific properties. """ holdoutStatus: HoldoutStatus - includedRules: Optional[list[str]] # None = global holdout; list of rule IDs = local holdout + # Per-rule targeting for local holdouts. Scope comes from the datafile section, + # not this field; required on 'localHoldouts' entries, stripped on 'holdouts'. + includedRules: Optional[list[str]] diff --git a/optimizely/project_config.py b/optimizely/project_config.py index 5ec5f85bf..728bf89af 100644 --- a/optimizely/project_config.py +++ b/optimizely/project_config.py @@ -90,17 +90,49 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): self.region: str = region_value or 'US' # Parse holdouts from datafile and convert to Holdout entities - holdouts_data: list[types.HoldoutDict] = config.get('holdouts', []) + global_holdouts_data: list[types.HoldoutDict] = config.get('holdouts', []) + local_holdouts_data: list[types.HoldoutDict] = config.get('localHoldouts', []) self.holdouts: list[entities.Holdout] = [] self.holdout_id_map: dict[str, entities.Holdout] = {} - # Global holdouts (includedRules is None) — evaluated at flag level before any rule + # Global holdouts — evaluated at flag level before any rule self.global_holdouts: list[entities.Holdout] = [] # Rule-level holdouts — map from rule ID to holdouts targeting that rule self.rule_holdouts_map: dict[str, list[entities.Holdout]] = {} - # Convert holdout dicts to Holdout entities - for holdout_data in holdouts_data: - # Create Holdout entity + # Process global holdouts: section membership is the sole signal for scope. + # Drop any 'includedRules' field on entries here so the entity is unambiguously + # global (is_global → True), even if the datafile incorrectly includes one. + for holdout_data in global_holdouts_data: + sanitized = cast(types.HoldoutDict, dict(holdout_data)) + if sanitized.pop('includedRules', None) is not None: # type: ignore[misc] + self.logger.warning( + f'Global holdout "{holdout_data.get("key", "")}" ' + f'(id: {holdout_data.get("id", "")}) has "includedRules" ' + f'which will be ignored; global holdouts apply to all flags.' + ) + holdout = entities.Holdout(**sanitized) + self.holdouts.append(holdout) + + # Only process Running holdouts + if not holdout.is_activated: + continue + + # Map by ID for quick lookup + self.holdout_id_map[holdout.id] = holdout + self.global_holdouts.append(holdout) + + # Process local holdouts: every entry must carry 'includedRules' (list of rule IDs). + # Entries without 'includedRules' are invalid per spec — log an error and exclude + # them from evaluation (do NOT fall back to global application). + for holdout_data in local_holdouts_data: + if 'includedRules' not in holdout_data or holdout_data.get('includedRules') is None: + holdout_id = holdout_data.get('id', '') + self.logger.error( + f'Local holdout with ID "{holdout_id}" is missing required "includedRules" ' + f'field and will be excluded from evaluation.' + ) + continue + holdout = entities.Holdout(**holdout_data) self.holdouts.append(holdout) @@ -111,15 +143,11 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): # Map by ID for quick lookup self.holdout_id_map[holdout.id] = holdout - # Classify holdout as global or local based on includedRules - if holdout.is_global: - self.global_holdouts.append(holdout) - else: - # Local holdout — register for each targeted rule ID - for rule_id in (holdout.included_rules or []): - if rule_id not in self.rule_holdouts_map: - self.rule_holdouts_map[rule_id] = [] - self.rule_holdouts_map[rule_id].append(holdout) + # Register for each targeted rule ID + for rule_id in (holdout.included_rules or []): + if rule_id not in self.rule_holdouts_map: + self.rule_holdouts_map[rule_id] = [] + self.rule_holdouts_map[rule_id].append(holdout) # Utility maps for quick lookup self.group_id_map: dict[str, entities.Group] = self._generate_key_map(self.groups, 'id', entities.Group) @@ -887,9 +915,11 @@ def get_flag_variation( return None def get_global_holdouts(self) -> list[entities.Holdout]: - """Return all global holdouts (includedRules is None). + """Return all global holdouts (parsed from the top-level 'holdouts' section). Global holdouts are evaluated at flag level before any rule is checked. + Section membership in 'holdouts' is the sole signal for global scope — + any 'includedRules' field on these entries is ignored. Returns: List of global Holdout entities that are currently running. @@ -899,9 +929,11 @@ def get_global_holdouts(self) -> list[entities.Holdout]: def get_holdouts_for_rule(self, rule_id: str) -> list[entities.Holdout]: """Return local holdouts that target a specific rule. - Local holdouts are evaluated per-rule, before the rule's audience and - traffic allocation checks. A rule ID not present in any holdout's - includedRules simply returns an empty list — silently skipped. + Local holdouts come from the top-level 'localHoldouts' datafile section and + are scoped per-rule via their 'includedRules' field. They are evaluated + before the rule's audience and traffic allocation checks. A rule ID not + present in any holdout's includedRules simply returns an empty list — + silently skipped. Args: rule_id: The experiment or delivery rule ID to look up. diff --git a/tests/test_decision_service_holdout.py b/tests/test_decision_service_holdout.py index 1bf81c937..21a269b2a 100644 --- a/tests/test_decision_service_holdout.py +++ b/tests/test_decision_service_holdout.py @@ -1380,9 +1380,33 @@ def tearDown(self): if hasattr(self, 'opt_obj'): self.opt_obj.close() - def _make_opt(self, holdouts): + def _make_opt(self, holdouts, local_holdouts=None): + """Build an Optimizely instance from holdout entries. + + Per FSSDK-12760, the datafile partitions holdouts into two top-level sections: + - 'holdouts' → global holdouts (every entry is global, regardless of includedRules) + - 'localHoldouts' → local holdouts (rule-scoped via includedRules) + + For convenience, this helper auto-routes entries: any entry in `holdouts` + whose `includedRules` is a non-None list is moved to the `localHoldouts` + section. Tests that explicitly want to control sectioning can pass both + `holdouts` and `local_holdouts` lists. + """ cfg = self.config_dict_with_features.copy() - cfg['holdouts'] = holdouts + if local_holdouts is None: + globals_list: list = [] + locals_list: list = [] + for h in holdouts: + if h.get('includedRules') is not None: + locals_list.append(h) + else: + globals_list.append(h) + cfg['holdouts'] = globals_list + if locals_list: + cfg['localHoldouts'] = locals_list + else: + cfg['holdouts'] = holdouts + cfg['localHoldouts'] = local_holdouts self.opt_obj = optimizely_module.Optimizely(json.dumps(cfg)) return self.opt_obj diff --git a/tests/test_holdout_config.py b/tests/test_holdout_config.py index 3d8cd08c9..6420e42c1 100644 --- a/tests/test_holdout_config.py +++ b/tests/test_holdout_config.py @@ -12,13 +12,25 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Level 1 tests for holdout config parsing and data model (FSSDK-12369). +"""Level 1 tests for holdout config parsing and data model. + +Originally added under FSSDK-12369 to cover holdout config classification. +Updated under FSSDK-12760 to align with the backward-compatible local holdouts +design: local holdouts now live in a new top-level 'localHoldouts' datafile +section. The 'holdouts' section carries ONLY global holdouts — section membership +(not 'includedRules') is the sole signal for scope. Tests cover: -- isGlobal classification (includedRules == None vs list) -- get_global_holdouts() returns only global holdouts -- get_holdouts_for_rule() returns local holdouts for a specific rule -- Backward compatibility with old datafiles (no includedRules field) +- isGlobal classification at the entity level (includedRules == None vs list) +- get_global_holdouts() returns entries from the 'holdouts' section +- get_holdouts_for_rule() returns entries from the 'localHoldouts' section +- Backward compatibility: + * Old datafiles without 'localHoldouts' continue to work unchanged + * Any 'includedRules' field on entries in the 'holdouts' section is ignored + * Datafiles missing both 'holdouts' and 'localHoldouts' sections produce + empty global/local lists +- localHoldouts section: invalid entries (missing includedRules) are logged + and excluded from evaluation - Edge cases: empty array vs None, unknown rule IDs, cross-flag targeting """ @@ -59,10 +71,24 @@ def _make_holdout( return h -def _build_config(holdouts: list, base_test: 'base.BaseTest') -> 'optimizely_module.Optimizely': - """Create an Optimizely instance with the given holdouts list.""" +def _build_config( + holdouts: list, + base_test: 'base.BaseTest', + local_holdouts: 'list | None' = None, +) -> 'optimizely_module.Optimizely': + """Create an Optimizely instance with the given top-level holdout sections. + + Args: + holdouts: Entries for the top-level 'holdouts' section (treated as global). + base_test: Test fixture providing config_dict_with_features. + local_holdouts: Optional entries for the top-level 'localHoldouts' section + (treated as local). When omitted, the 'localHoldouts' key is NOT added + to the datafile, exercising backward-compatible behavior. + """ config_dict = base_test.config_dict_with_features.copy() config_dict['holdouts'] = holdouts + if local_holdouts is not None: + config_dict['localHoldouts'] = local_holdouts return optimizely_module.Optimizely(json.dumps(config_dict)) @@ -131,13 +157,23 @@ def tearDown(self): if hasattr(self, 'opt_obj'): self.opt_obj.close() - def test_get_global_holdouts_returns_all_global_holdouts(self): - """All holdouts without includedRules should be returned.""" - self.opt_obj = _build_config([ - _make_holdout('h1', 'global_1'), # field absent → global - _make_holdout('h2', 'global_2', None), # explicitly None → global - _make_holdout('h3', 'local_1', ['rule_x']), # local - ], self) + def test_get_global_holdouts_returns_all_entries_from_holdouts_section(self): + """Every entry in the 'holdouts' datafile section is treated as global. + + Section membership is the sole signal for scope — any 'includedRules' + field on these entries is ignored. Local holdouts must live in the + separate 'localHoldouts' section. + """ + self.opt_obj = _build_config( + holdouts=[ + _make_holdout('h1', 'global_1'), + _make_holdout('h2', 'global_2', None), + ], + base_test=self, + local_holdouts=[ + _make_holdout('h3', 'local_1', ['rule_x']), + ], + ) config = self.opt_obj.config_manager.get_config() global_holdouts = config.get_global_holdouts() global_ids = {h.id for h in global_holdouts} @@ -164,14 +200,47 @@ def test_get_global_holdouts_excludes_non_running_holdouts(self): self.assertNotIn('h_draft', ids) def test_get_global_holdouts_returns_empty_when_all_local(self): - """If all holdouts are local, global list is empty.""" - self.opt_obj = _build_config([ - _make_holdout('h1', 'local_a', ['rule_1']), - _make_holdout('h2', 'local_b', ['rule_2']), - ], self) + """If all holdouts live in the localHoldouts section, global list is empty.""" + self.opt_obj = _build_config( + holdouts=[], + base_test=self, + local_holdouts=[ + _make_holdout('h1', 'local_a', ['rule_1']), + _make_holdout('h2', 'local_b', ['rule_2']), + ], + ) config = self.opt_obj.config_manager.get_config() self.assertEqual(config.get_global_holdouts(), []) + def test_global_holdouts_ignore_included_rules_on_entries(self): + """Any 'includedRules' field on entries in the 'holdouts' section is ignored. + + Section membership in 'holdouts' alone determines global scope. Even if the + datafile incorrectly includes an 'includedRules' field on a global holdout, + the entity must still be classified as global and never registered against + any rule's local-holdout map. + """ + self.opt_obj = _build_config( + holdouts=[ + _make_holdout('h_global_with_rules', 'g', ['rule_should_be_ignored']), + ], + base_test=self, + ) + config = self.opt_obj.config_manager.get_config() + + global_holdouts = config.get_global_holdouts() + global_ids = {h.id for h in global_holdouts} + self.assertIn('h_global_with_rules', global_ids) + + # The ignored rule ID must not be present in the rule map + self.assertEqual(config.get_holdouts_for_rule('rule_should_be_ignored'), []) + + # The entity itself must report is_global (includedRules was stripped) + for h in global_holdouts: + if h.id == 'h_global_with_rules': + self.assertTrue(h.is_global) + self.assertIsNone(h.included_rules) + class HoldoutConfigGetHoldoutsForRuleTest(unittest.TestCase): """Tests for ProjectConfig.get_holdouts_for_rule().""" @@ -185,9 +254,13 @@ def tearDown(self): def test_get_holdouts_for_rule_returns_matching_local_holdouts(self): """Holdout targeting rule_x should be returned for rule_x.""" - self.opt_obj = _build_config([ - _make_holdout('h1', 'local_h', ['rule_x', 'rule_y']), - ], self) + self.opt_obj = _build_config( + holdouts=[], + base_test=self, + local_holdouts=[ + _make_holdout('h1', 'local_h', ['rule_x', 'rule_y']), + ], + ) config = self.opt_obj.config_manager.get_config() holdouts = config.get_holdouts_for_rule('rule_x') self.assertEqual(len(holdouts), 1) @@ -195,9 +268,13 @@ def test_get_holdouts_for_rule_returns_matching_local_holdouts(self): def test_get_holdouts_for_rule_returns_empty_for_unknown_rule(self): """Rule ID not found in any holdout's includedRules returns empty list.""" - self.opt_obj = _build_config([ - _make_holdout('h1', 'local_h', ['rule_a']), - ], self) + self.opt_obj = _build_config( + holdouts=[], + base_test=self, + local_holdouts=[ + _make_holdout('h1', 'local_h', ['rule_a']), + ], + ) config = self.opt_obj.config_manager.get_config() # Silently skip unknown rule IDs holdouts = config.get_holdouts_for_rule('nonexistent_rule') @@ -211,10 +288,14 @@ def test_get_holdouts_for_rule_returns_empty_when_no_holdouts(self): def test_get_holdouts_for_rule_multiple_holdouts_for_same_rule(self): """Multiple holdouts can target the same rule.""" - self.opt_obj = _build_config([ - _make_holdout('h1', 'local_h1', ['rule_x']), - _make_holdout('h2', 'local_h2', ['rule_x', 'rule_y']), - ], self) + self.opt_obj = _build_config( + holdouts=[], + base_test=self, + local_holdouts=[ + _make_holdout('h1', 'local_h1', ['rule_x']), + _make_holdout('h2', 'local_h2', ['rule_x', 'rule_y']), + ], + ) config = self.opt_obj.config_manager.get_config() holdouts = config.get_holdouts_for_rule('rule_x') ids = {h.id for h in holdouts} @@ -223,10 +304,15 @@ def test_get_holdouts_for_rule_multiple_holdouts_for_same_rule(self): def test_get_holdouts_for_rule_does_not_return_global_holdouts(self): """Global holdouts should not appear in get_holdouts_for_rule results.""" - self.opt_obj = _build_config([ - _make_holdout('global', 'global_holdout'), # field absent → global - _make_holdout('local', 'local_holdout', ['rule_x']), - ], self) + self.opt_obj = _build_config( + holdouts=[ + _make_holdout('global', 'global_holdout'), + ], + base_test=self, + local_holdouts=[ + _make_holdout('local', 'local_holdout', ['rule_x']), + ], + ) config = self.opt_obj.config_manager.get_config() holdouts = config.get_holdouts_for_rule('rule_x') ids = {h.id for h in holdouts} @@ -235,17 +321,25 @@ def test_get_holdouts_for_rule_does_not_return_global_holdouts(self): def test_get_holdouts_for_rule_rule_specificity(self): """A holdout targeting rule_x must not appear for rule_y.""" - self.opt_obj = _build_config([ - _make_holdout('h1', 'local_for_x', ['rule_x']), - ], self) + self.opt_obj = _build_config( + holdouts=[], + base_test=self, + local_holdouts=[ + _make_holdout('h1', 'local_for_x', ['rule_x']), + ], + ) config = self.opt_obj.config_manager.get_config() self.assertEqual(config.get_holdouts_for_rule('rule_y'), []) def test_get_holdouts_for_rule_cross_flag_targeting(self): """One holdout can target rules from multiple different flags.""" - self.opt_obj = _build_config([ - _make_holdout('h1', 'cross_flag_holdout', ['rule_flag_a', 'rule_flag_b']), - ], self) + self.opt_obj = _build_config( + holdouts=[], + base_test=self, + local_holdouts=[ + _make_holdout('h1', 'cross_flag_holdout', ['rule_flag_a', 'rule_flag_b']), + ], + ) config = self.opt_obj.config_manager.get_config() for rule_id in ['rule_flag_a', 'rule_flag_b']: holdouts = config.get_holdouts_for_rule(rule_id) @@ -263,9 +357,13 @@ def tearDown(self): if hasattr(self, 'opt_obj'): self.opt_obj.close() - def test_old_datafile_without_included_rules_treated_as_global(self): - """Datafiles without includedRules field must default to global holdout.""" - # Simulate old datafile — no 'includedRules' key at all + def test_old_datafile_without_local_holdouts_section_works(self): + """Old datafiles that only emit the 'holdouts' section continue to work. + + Per FSSDK-12760: backward compatibility requires that datafiles produced + before the 'localHoldouts' section existed are parsed exactly like before. + Every entry in 'holdouts' is global; no errors, no log noise. + """ old_holdout = { 'id': 'old_h', 'key': 'legacy_holdout', @@ -283,7 +381,7 @@ def test_old_datafile_without_included_rules_treated_as_global(self): self.assertTrue(global_holdouts[0].is_global) def test_old_datafile_holdout_does_not_appear_in_rule_map(self): - """Legacy holdouts with no includedRules field must not pollute rule map.""" + """Legacy holdouts (no localHoldouts section) must not pollute rule map.""" old_holdout = { 'id': 'old_h', 'key': 'legacy_holdout', @@ -296,17 +394,251 @@ def test_old_datafile_holdout_does_not_appear_in_rule_map(self): config = self.opt_obj.config_manager.get_config() self.assertEqual(config.get_holdouts_for_rule('any_rule'), []) - def test_empty_included_rules_is_local_not_global(self): - """[] (empty array) is a local holdout targeting no rules — not the same as None.""" - holdout_empty = _make_holdout('h_empty', 'empty_local', included_rules=[]) - holdout_none = _make_holdout('h_none', 'global_none', included_rules=None) + def test_datafile_missing_both_holdouts_sections(self): + """Datafiles without 'holdouts' or 'localHoldouts' keys produce empty lists.""" + config_dict = self.config_dict_with_features.copy() + # Explicitly do not set either holdouts key + self.opt_obj = optimizely_module.Optimizely(json.dumps(config_dict)) + config = self.opt_obj.config_manager.get_config() + + self.assertEqual(config.get_global_holdouts(), []) + self.assertEqual(config.get_holdouts_for_rule('any_rule'), []) + + def test_is_global_entity_property_independent_of_section(self): + """The Holdout.is_global entity property still reflects includedRules. + + At the entity level, is_global is computed from the included_rules attribute + (None → True, [] or non-empty list → False). The new datafile sections affect + how the entity is BUILT (via includedRules stripping) but not how the property + itself is computed. + """ + # Build an entity directly (bypassing project config) — includedRules controls is_global + h_none = entities.Holdout( + id='h_none', key='g', status='Running', + variations=HOLDOUT_VARIATION, trafficAllocation=FULL_TRAFFIC, + audienceIds=[], includedRules=None, + ) + h_empty = entities.Holdout( + id='h_empty', key='l', status='Running', + variations=HOLDOUT_VARIATION, trafficAllocation=FULL_TRAFFIC, + audienceIds=[], includedRules=[], + ) + self.assertTrue(h_none.is_global) + self.assertFalse(h_empty.is_global) + + +class LocalHoldoutsSectionTest(unittest.TestCase): + """Tests for the new top-level 'localHoldouts' datafile section (FSSDK-12760). + + Local holdouts now live in a dedicated 'localHoldouts' section, separate from + 'holdouts' which carries only global holdouts. Older SDK versions (Gen 1/Gen 2) + will ignore this unknown top-level key entirely — that's the whole point of the + backward-compatible design — but Gen 3 SDKs must parse it as the source of truth + for local (rule-scoped) holdouts. + """ + + def setUp(self): + base.BaseTest.setUp(self) + + def tearDown(self): + if hasattr(self, 'opt_obj'): + self.opt_obj.close() - self.opt_obj = _build_config([holdout_empty, holdout_none], self) + def test_local_holdouts_section_registers_in_rule_map(self): + """Entries in 'localHoldouts' are registered under each rule in includedRules.""" + self.opt_obj = _build_config( + holdouts=[], + base_test=self, + local_holdouts=[ + _make_holdout('h_local', 'local_h', ['rule_x']), + ], + ) config = self.opt_obj.config_manager.get_config() + holdouts = config.get_holdouts_for_rule('rule_x') + self.assertEqual(len(holdouts), 1) + self.assertEqual(holdouts[0].id, 'h_local') + + def test_local_holdouts_section_entries_excluded_from_global_list(self): + """Entries in 'localHoldouts' must not appear in get_global_holdouts().""" + self.opt_obj = _build_config( + holdouts=[], + base_test=self, + local_holdouts=[ + _make_holdout('h_local', 'local_h', ['rule_x']), + ], + ) + config = self.opt_obj.config_manager.get_config() + self.assertEqual(config.get_global_holdouts(), []) - global_holdouts = config.get_global_holdouts() - global_ids = {h.id for h in global_holdouts} + def test_local_holdouts_missing_included_rules_logged_and_excluded(self): + """Entries in 'localHoldouts' without 'includedRules' are invalid per spec. + + SDK must log an error and exclude the entry from evaluation. It must NOT + fall back to global application (the partition between sections is hard). + """ + invalid_local = { + 'id': 'h_invalid', + 'key': 'invalid_local', + 'status': 'Running', + 'audienceIds': [], + 'variations': HOLDOUT_VARIATION, + 'trafficAllocation': FULL_TRAFFIC, + # Note: no 'includedRules' field + } + self.opt_obj = _build_config( + holdouts=[], + base_test=self, + local_holdouts=[invalid_local], + ) + config = self.opt_obj.config_manager.get_config() + + # Invalid entry must not be applied as global + self.assertEqual(config.get_global_holdouts(), []) + # Invalid entry must not be applied as local for any rule + self.assertEqual(config.get_holdouts_for_rule('any_rule'), []) + # Invalid entry must not be retrievable by ID either + self.assertIsNone(config.holdout_id_map.get('h_invalid')) + + def test_local_holdouts_missing_included_rules_logs_error(self): + """Verify an error log is emitted for an invalid local holdout entry.""" + invalid_local = { + 'id': 'h_invalid', + 'key': 'invalid_local', + 'status': 'Running', + 'audienceIds': [], + 'variations': HOLDOUT_VARIATION, + 'trafficAllocation': FULL_TRAFFIC, + } + config_dict = self.config_dict_with_features.copy() + config_dict['localHoldouts'] = [invalid_local] + + # Verify the error is logged through the standard logging framework. + with self.assertLogs('optimizely.logger', level='ERROR') as captured: + self.opt_obj = optimizely_module.Optimizely(json.dumps(config_dict)) + + matching = [ + msg for msg in captured.output + if 'h_invalid' in msg and 'includedRules' in msg + ] + self.assertGreaterEqual( + len(matching), 1, + f'Expected error log for invalid local holdout; got: {captured.output}' + ) + + def test_local_holdouts_with_null_included_rules_logged_and_excluded(self): + """includedRules=None in 'localHoldouts' is invalid (same as missing). + + Distinct from 'holdouts' section where None signals a global holdout — + in 'localHoldouts' the field is REQUIRED and a None value is invalid. + """ + invalid_local = _make_holdout('h_null', 'null_local', included_rules=None) + self.opt_obj = _build_config( + holdouts=[], + base_test=self, + local_holdouts=[invalid_local], + ) + config = self.opt_obj.config_manager.get_config() + self.assertEqual(config.get_holdouts_for_rule('any_rule'), []) + self.assertEqual(config.get_global_holdouts(), []) + + def test_local_holdouts_empty_included_rules_targets_no_rules(self): + """includedRules=[] is valid but targets no rules (entity is stored, not invalid). + + An entry with an empty includedRules list is treated as a local holdout + that simply does not apply to any rule. It is NOT invalid (no error log), + and it is NOT promoted to global. This matches the existing entity-level + semantics where [] != None. + """ + empty_local = _make_holdout('h_empty', 'empty_local', included_rules=[]) + self.opt_obj = _build_config( + holdouts=[], + base_test=self, + local_holdouts=[empty_local], + ) + config = self.opt_obj.config_manager.get_config() + # Not in any rule map (no rules to target) + self.assertEqual(config.get_holdouts_for_rule('any_rule'), []) + # Not global either + self.assertEqual(config.get_global_holdouts(), []) + # But the entity itself was created and tracked in holdout_id_map + stored = config.holdout_id_map.get('h_empty') + self.assertIsNotNone(stored) + self.assertFalse(stored.is_global) + + def test_local_holdouts_excludes_non_running_entries(self): + """Non-Running entries in 'localHoldouts' must not be evaluated.""" + self.opt_obj = _build_config( + holdouts=[], + base_test=self, + local_holdouts=[ + _make_holdout('h_running', 'lr', ['rule_x'], status='Running'), + _make_holdout('h_draft', 'ld', ['rule_x'], status='Draft'), + ], + ) + config = self.opt_obj.config_manager.get_config() + ids = {h.id for h in config.get_holdouts_for_rule('rule_x')} + self.assertIn('h_running', ids) + self.assertNotIn('h_draft', ids) - # None → global; [] → local (does not appear in global list) - self.assertIn('h_none', global_ids) - self.assertNotIn('h_empty', global_ids) + def test_both_sections_present_partition_correctly(self): + """When both 'holdouts' and 'localHoldouts' are present, scope is enforced + by section membership — entries never cross over.""" + self.opt_obj = _build_config( + holdouts=[ + _make_holdout('g1', 'global_1'), + _make_holdout('g2', 'global_2'), + ], + base_test=self, + local_holdouts=[ + _make_holdout('l1', 'local_1', ['rule_a']), + _make_holdout('l2', 'local_2', ['rule_b']), + ], + ) + config = self.opt_obj.config_manager.get_config() + + global_ids = {h.id for h in config.get_global_holdouts()} + self.assertEqual(global_ids, {'g1', 'g2'}) + + self.assertEqual({h.id for h in config.get_holdouts_for_rule('rule_a')}, {'l1'}) + self.assertEqual({h.id for h in config.get_holdouts_for_rule('rule_b')}, {'l2'}) + + def test_local_holdouts_id_uniqueness_across_sections(self): + """Entries from both sections are tracked together in holdout_id_map. + + get_holdout(id) must work for both global and local holdouts regardless of + which section they came from. + """ + self.opt_obj = _build_config( + holdouts=[ + _make_holdout('g1', 'global_1'), + ], + base_test=self, + local_holdouts=[ + _make_holdout('l1', 'local_1', ['rule_x']), + ], + ) + config = self.opt_obj.config_manager.get_config() + + self.assertIsNotNone(config.get_holdout('g1')) + self.assertIsNotNone(config.get_holdout('l1')) + + def test_local_holdouts_section_with_real_traffic_allocation(self): + """Local holdouts in 'localHoldouts' carry real trafficAllocation directly. + + Per spec: no more dummy-zero-allocation workaround — the trafficAllocation + field is used as-is for bucketing. + """ + local_h = _make_holdout('h_local', 'local_h', ['rule_x']) + # Override with a custom traffic allocation + local_h['trafficAllocation'] = [{'entityId': 'holdout_var_1', 'endOfRange': 5000}] + + self.opt_obj = _build_config( + holdouts=[], + base_test=self, + local_holdouts=[local_h], + ) + config = self.opt_obj.config_manager.get_config() + holdouts = config.get_holdouts_for_rule('rule_x') + self.assertEqual(len(holdouts), 1) + self.assertEqual(holdouts[0].trafficAllocation, + [{'entityId': 'holdout_var_1', 'endOfRange': 5000}]) From a1e0da88ad8d0fb639817e21f0f5b48d23b9e280 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Thu, 2 Jul 2026 08:35:10 -0700 Subject: [PATCH 23/32] [AI-FSSDK] [FSSDK-12813] Normalize decision event campaign_id, variation_id, and entity_id (#518) * [FSSDK-12813] Normalize decision event campaign_id, variation_id, and entity_id * [FSSDK-12813] Relax campaign_id/entity_id validation to non-empty string per updated spec * [FSSDK-12813] Remove ticket references from code comments per cross-sdk guideline * [FSSDK-12813] Use TypeGuard for ID predicates to drop type: ignore * [FSSDK-12813] Add 2026 to copyright year in changed files * [FSSDK-12813] Trigger CI * Refactor comments for clarity and remove spec references in event ID normalization and holdout configuration tests --------- Co-authored-by: Farhan Anjum --- optimizely/event/event_factory.py | 14 +- optimizely/event/event_id_normalizer.py | 93 ++++++++++ optimizely/event/payload.py | 10 +- optimizely/event_builder.py | 18 +- optimizely/project_config.py | 2 +- tests/test_event_factory.py | 213 +++++++++++++++++++++- tests/test_event_id_normalizer.py | 233 ++++++++++++++++++++++++ tests/test_holdout_config.py | 2 +- 8 files changed, 571 insertions(+), 14 deletions(-) create mode 100644 optimizely/event/event_id_normalizer.py create mode 100644 tests/test_event_id_normalizer.py diff --git a/optimizely/event/event_factory.py b/optimizely/event/event_factory.py index f66c1d595..b6a9c02ae 100644 --- a/optimizely/event/event_factory.py +++ b/optimizely/event/event_factory.py @@ -1,4 +1,4 @@ -# Copyright 2019, 2022, Optimizely +# Copyright 2019, 2022, 2026, Optimizely # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -18,6 +18,7 @@ from optimizely.helpers import enums from optimizely.helpers import event_tag_utils from optimizely.helpers import validator +from . import event_id_normalizer from . import log_event from . import payload from . import user_event @@ -134,12 +135,19 @@ def _create_visitor(cls, event: Optional[user_event.UserEvent], logger: Logger) if isinstance(event.experiment, entities.Experiment): experiment_layerId = event.experiment.layerId + normalized_campaign_id = event_id_normalizer.normalize_campaign_id( + experiment_layerId, experiment_id + ) + normalized_variation_id = event_id_normalizer.normalize_variation_id(variation_id) + metadata = payload.Metadata(event.flag_key, event.rule_key, event.rule_type, variation_key, event.enabled, event.cmab_uuid) - decision = payload.Decision(experiment_layerId, experiment_id, variation_id, metadata) + decision = payload.Decision( + normalized_campaign_id, experiment_id, normalized_variation_id, metadata + ) snapshot_event = payload.SnapshotEvent( - experiment_layerId, event.uuid, cls.ACTIVATE_EVENT_KEY, event.timestamp, + normalized_campaign_id, event.uuid, cls.ACTIVATE_EVENT_KEY, event.timestamp, ) snapshot = payload.Snapshot([snapshot_event], [decision]) diff --git a/optimizely/event/event_id_normalizer.py b/optimizely/event/event_id_normalizer.py new file mode 100644 index 000000000..f2d4235d1 --- /dev/null +++ b/optimizely/event/event_id_normalizer.py @@ -0,0 +1,93 @@ +# Copyright 2026, Optimizely +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Normalization helpers for decision-event ID fields. + +This module provides byte-equivalent, cross-SDK normalization for the +``campaign_id``, ``variation_id``, and impression ``entity_id`` fields that +appear in dispatched decision events. + +Rules: + * ``campaign_id`` and impression ``entity_id`` accept **any non-empty + string** (numeric like ``"12345"`` or opaque like ``"default-12345"`` / + ``"layer_abc"``). The fallback to ``experiment_id`` fires ONLY when the + value is the empty string, ``None``, or missing. Non-string types are + out of scope for this normalization path (the upstream datafile + producer delivers string or null values). + * ``variation_id`` retains the stricter contract: it MUST be a non-empty + string of decimal digits ``0-9`` (leading zeros allowed). Empty, + whitespace, non-string, and non-numeric inputs are normalized to + ``None`` so the wire payload carries an explicit null. + * ``entity_id`` on impression events shares the campaign_id normalization + and is therefore byte-equivalent to the normalized campaign_id for the + same impression. + +The normalization path MUST NOT log, warn, or raise. It must never drop or +defer event dispatch. +""" + + +from sys import version_info +from typing import Any, Optional + +if version_info < (3, 10): + from typing_extensions import TypeGuard +else: + from typing import TypeGuard + + +def is_non_empty_string(value: Any) -> TypeGuard[str]: + """Return ``True`` if ``value`` is a non-empty :class:`str`. + Any non-empty string is accepted regardless of + character content (IDs may be opaque, e.g. ``"default-12345"``). + """ + return isinstance(value, str) and value != '' + + +def is_numeric_id_string(value: Any) -> TypeGuard[str]: + """Return ``True`` if ``value`` is a non-empty decimal-digit string. + Whitespace, signs, decimal points, exponents + and non-string types all return ``False``. Leading + zeros are accepted. + """ + if not isinstance(value, str): + return False + if value == '': + return False + return value.isascii() and value.isdigit() + + +def normalize_campaign_id(campaign_id: Any, experiment_id: Any) -> str: + """Normalize a decision-event ``campaign_id``. + + Returns ``campaign_id`` unchanged when it is a non-empty string (any + character content — numeric like ``"12345"`` or opaque like + ``"default-12345"``). Otherwise falls back to ``experiment_id`` (when it + is itself a non-empty string). If neither is a non-empty string, returns + an empty string so the event still dispatches. + """ + if is_non_empty_string(campaign_id): + return campaign_id + if is_non_empty_string(experiment_id): + return experiment_id + return '' + + +def normalize_variation_id(variation_id: Any) -> Optional[str]: + """Normalize a decision-event ``variation_id``. + + Returns the original value if it is a valid numeric ID string. Otherwise + returns ``None`` so the event payload carries an explicit null for the + downstream consumer. + """ + return variation_id if is_numeric_id_string(variation_id) else None diff --git a/optimizely/event/payload.py b/optimizely/event/payload.py index e352dd10f..a87f97e27 100644 --- a/optimizely/event/payload.py +++ b/optimizely/event/payload.py @@ -1,4 +1,4 @@ -# Copyright 2019, 2022, Optimizely +# Copyright 2019, 2022, 2026, Optimizely # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -71,7 +71,13 @@ def get_event_params(self) -> dict[str, Any]: class Decision: """ Class respresenting Decision. """ - def __init__(self, campaign_id: str, experiment_id: str, variation_id: str, metadata: Metadata): + def __init__( + self, + campaign_id: str, + experiment_id: str, + variation_id: Optional[str], + metadata: Metadata, + ): self.campaign_id = campaign_id self.experiment_id = experiment_id self.variation_id = variation_id diff --git a/optimizely/event_builder.py b/optimizely/event_builder.py index e9c9fd44a..7ef6b347a 100644 --- a/optimizely/event_builder.py +++ b/optimizely/event_builder.py @@ -1,4 +1,4 @@ -# Copyright 2016-2019, 2022, Optimizely +# Copyright 2016-2019, 2022, 2026, Optimizely # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -18,6 +18,7 @@ from sys import version_info from . import version +from .event import event_id_normalizer from .helpers import enums from .helpers import event_tag_utils from .helpers import validator @@ -178,7 +179,7 @@ def _get_common_params( def _get_required_params_for_impression( self, experiment: Experiment, variation_id: str - ) -> dict[str, list[dict[str, str | int]]]: + ) -> dict[str, list[dict[str, Any]]]: """ Get parameters that are required for the impression event to register. Args: @@ -188,19 +189,24 @@ def _get_required_params_for_impression( Returns: Dict consisting of decisions and events info for impression event. """ - snapshot: dict[str, list[dict[str, str | int]]] = {} + snapshot: dict[str, list[dict[str, Any]]] = {} + + normalized_campaign_id = event_id_normalizer.normalize_campaign_id( + experiment.layerId, experiment.id + ) + normalized_variation_id = event_id_normalizer.normalize_variation_id(variation_id) snapshot[self.EventParams.DECISIONS] = [ { self.EventParams.EXPERIMENT_ID: experiment.id, - self.EventParams.VARIATION_ID: variation_id, - self.EventParams.CAMPAIGN_ID: experiment.layerId, + self.EventParams.VARIATION_ID: normalized_variation_id, + self.EventParams.CAMPAIGN_ID: normalized_campaign_id, } ] snapshot[self.EventParams.EVENTS] = [ { - self.EventParams.EVENT_ID: experiment.layerId, + self.EventParams.EVENT_ID: normalized_campaign_id, self.EventParams.TIME: self._get_time(), self.EventParams.KEY: 'campaign_activated', self.EventParams.UUID: str(uuid.uuid4()), diff --git a/optimizely/project_config.py b/optimizely/project_config.py index 728bf89af..a7152ae83 100644 --- a/optimizely/project_config.py +++ b/optimizely/project_config.py @@ -122,7 +122,7 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): self.global_holdouts.append(holdout) # Process local holdouts: every entry must carry 'includedRules' (list of rule IDs). - # Entries without 'includedRules' are invalid per spec — log an error and exclude + # Entries without 'includedRules' are invalid — log an error and exclude # them from evaluation (do NOT fall back to global application). for holdout_data in local_holdouts_data: if 'includedRules' not in holdout_data or holdout_data.get('includedRules') is None: diff --git a/tests/test_event_factory.py b/tests/test_event_factory.py index 6d70c713c..b86a15440 100644 --- a/tests/test_event_factory.py +++ b/tests/test_event_factory.py @@ -1,4 +1,4 @@ -# Copyright 2019, Optimizely +# Copyright 2019, 2026, Optimizely # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -1237,3 +1237,214 @@ def test_create_impression_event_without_cmab_uuid(self): EventFactory.HTTP_VERB, EventFactory.HTTP_HEADERS, ) + + +class EventFactoryIdNormalizationIntegrationTest(base.BaseTest): + """End-to-end decision-event ID normalization. + + These tests build real ``ImpressionEvent`` instances using crafted + Experiment/Variation objects, then call ``EventFactory.create_log_event`` + and inspect the dispatched payload. + """ + + def setUp(self, *args, **kwargs): + base.BaseTest.setUp(self, 'config_dict_with_multiple_experiments') + self.logger = logger.NoOpLogger() + + def _build_impression( + self, + experiment_id, + layer_id, + variation_id, + rule_type='experiment', + ): + """Build an ImpressionEvent with the provided raw ID values. + + ``experiment_id``/``layer_id``/``variation_id`` are inserted verbatim + so tests can exercise empty/non-string/non-numeric inputs. + """ + from optimizely.entities import Experiment, Variation + from optimizely.event.user_event import EventContext, ImpressionEvent + + experiment = Experiment( + id=experiment_id, + key='exp_key', + status='Running', + audienceIds=[], + variations=[], + forcedVariations={}, + trafficAllocation=[], + layerId=layer_id, + ) + variation = Variation( + id=variation_id, + key='variation_key', + featureEnabled=True, + ) if isinstance(variation_id, str) else None + + event_context = EventContext( + account_id='12001', + project_id='111001', + revision='42', + anonymize_ip=False, + region='US', + ) + return ImpressionEvent( + event_context=event_context, + user_id='test_user', + experiment=experiment, + visitor_attributes=[], + variation=variation, + flag_key='flag_key', + rule_key='rule_key', + rule_type=rule_type, + enabled=True, + ) + + def _dispatched_decision(self, impression_event): + """Return (decision_dict, event_dict) for an impression event.""" + log_event = EventFactory.create_log_event(impression_event, self.logger) + snapshot = log_event.params['visitors'][0]['snapshots'][0] + return snapshot['decisions'][0], snapshot['events'][0] + + def test_valid_campaign_id_is_passed_through(self): + impression = self._build_impression('111127', '111182', '111129') + decision, event = self._dispatched_decision(impression) + self.assertEqual('111182', decision['campaign_id']) + # entity_id mirrors campaign_id byte-for-byte. + self.assertEqual(decision['campaign_id'], event['entity_id']) + + def test_empty_campaign_id_falls_back_to_experiment_id(self): + impression = self._build_impression('111127', '', '111129') + decision, event = self._dispatched_decision(impression) + self.assertEqual('111127', decision['campaign_id']) + self.assertEqual('111127', event['entity_id']) + + def test_opaque_string_campaign_id_passes_through(self): + impression = self._build_impression('111127', 'campaign_a', '111129') + decision, event = self._dispatched_decision(impression) + self.assertEqual('campaign_a', decision['campaign_id']) + self.assertEqual('campaign_a', event['entity_id']) + + def test_prefixed_opaque_campaign_id_passes_through(self): + # Holdout layer IDs are opaque strings like "default-12345". + impression = self._build_impression('111127', 'default-12345', '111129') + decision, event = self._dispatched_decision(impression) + self.assertEqual('default-12345', decision['campaign_id']) + self.assertEqual('default-12345', event['entity_id']) + + def test_whitespace_campaign_id_passes_through(self): + # Whitespace is a non-empty string; character-content validation is + # the upstream datafile producer's responsibility. + impression = self._build_impression('111127', ' ', '111129') + decision, event = self._dispatched_decision(impression) + self.assertEqual(' ', decision['campaign_id']) + self.assertEqual(' ', event['entity_id']) + + def test_valid_variation_id_is_passed_through(self): + impression = self._build_impression('111127', '111182', '111129') + decision, _ = self._dispatched_decision(impression) + self.assertEqual('111129', decision['variation_id']) + + def test_empty_variation_id_becomes_none(self): + impression = self._build_impression('111127', '111182', '') + decision, _ = self._dispatched_decision(impression) + self.assertIsNone(decision['variation_id']) + + def test_non_numeric_variation_id_becomes_none(self): + impression = self._build_impression('111127', '111182', 'variation_a') + decision, _ = self._dispatched_decision(impression) + self.assertIsNone(decision['variation_id']) + + def test_whitespace_variation_id_becomes_none(self): + impression = self._build_impression('111127', '111182', ' ') + decision, _ = self._dispatched_decision(impression) + self.assertIsNone(decision['variation_id']) + + def test_normalization_applies_to_rollout_decisions(self): + impression = self._build_impression( + '111127', '', 'bad_var', rule_type='rollout' + ) + decision, event = self._dispatched_decision(impression) + self.assertEqual('111127', decision['campaign_id']) + self.assertIsNone(decision['variation_id']) + self.assertEqual('111127', event['entity_id']) + + def test_normalization_applies_to_feature_test_decisions(self): + impression = self._build_impression( + '111127', '', '', rule_type='feature-test' + ) + decision, event = self._dispatched_decision(impression) + self.assertEqual('111127', decision['campaign_id']) + self.assertIsNone(decision['variation_id']) + self.assertEqual('111127', event['entity_id']) + + def test_normalization_applies_to_holdout_decisions(self): + impression = self._build_impression( + '111127', '', '', rule_type='holdout' + ) + decision, event = self._dispatched_decision(impression) + self.assertEqual('111127', decision['campaign_id']) + self.assertIsNone(decision['variation_id']) + self.assertEqual('111127', event['entity_id']) + + def test_holdout_with_opaque_layer_id_passes_through(self): + # Canonical holdout case: opaque layerId like "default-12345" is a + # valid campaign_id and must not be replaced. + impression = self._build_impression( + '111127', 'default-12345', '111129', rule_type='holdout' + ) + decision, event = self._dispatched_decision(impression) + self.assertEqual('default-12345', decision['campaign_id']) + self.assertEqual('default-12345', event['entity_id']) + + def test_event_still_dispatches_when_all_ids_invalid(self): + """Event must still dispatch even when all IDs are invalid.""" + impression = self._build_impression('', '', '') + log_event = EventFactory.create_log_event(impression, self.logger) + self.assertIsNotNone(log_event) + decision, event = self._dispatched_decision(impression) + # campaign_id and entity_id end up as '' but the event still + # dispatches and the two fields remain byte-equivalent. + self.assertEqual('', decision['campaign_id']) + self.assertEqual('', event['entity_id']) + self.assertIsNone(decision['variation_id']) + + def test_entity_id_equals_campaign_id_byte_for_byte(self): + """``events[].entity_id`` must equal ``decisions[].campaign_id``.""" + for layer_id, exp_id, expected in [ + ('111182', '111127', '111182'), # numeric campaign_id wins + ('', '111127', '111127'), # empty falls back to experiment_id + # Opaque non-numeric IDs pass through unchanged. + ('default-12345', '111127', 'default-12345'), + ('layer_abc', '111127', 'layer_abc'), + ('007', '111127', '007'), # leading zeros preserved + ]: + with self.subTest(layer_id=layer_id, exp_id=exp_id): + impression = self._build_impression(exp_id, layer_id, '111129') + decision, event = self._dispatched_decision(impression) + self.assertEqual(expected, decision['campaign_id']) + self.assertEqual(decision['campaign_id'], event['entity_id']) + + def test_conversion_event_entity_id_unchanged(self): + """Conversion events derive entity_id from event.id, not the normalizer.""" + from optimizely.event.user_event_factory import UserEventFactory + + with mock.patch('time.time', return_value=42.123), mock.patch( + 'uuid.uuid4', return_value='a68cf1ad-0393-4e18-af87-efe8f01a7c9c' + ): + conversion_event = UserEventFactory.create_conversion_event( + self.project_config, + 'test_event', + 'test_user', + None, + None, + ) + log_event = EventFactory.create_log_event(conversion_event, self.logger) + snapshot = log_event.params['visitors'][0]['snapshots'][0] + # Conversion entity_id comes from the event.id of the conversion event + # and must NOT pass through the campaign_id normalizer. + self.assertEqual( + self.project_config.get_event('test_event').id, + snapshot['events'][0]['entity_id'], + ) diff --git a/tests/test_event_id_normalizer.py b/tests/test_event_id_normalizer.py new file mode 100644 index 000000000..ca261482e --- /dev/null +++ b/tests/test_event_id_normalizer.py @@ -0,0 +1,233 @@ +# Copyright 2026, Optimizely +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Unit tests for :mod:`optimizely.event.event_id_normalizer`.""" + +import unittest + +from optimizely.event import event_id_normalizer + + +class IsNonEmptyStringTest(unittest.TestCase): + """Cover :func:`event_id_normalizer.is_non_empty_string`. + + Any non-empty string is valid for ``campaign_id`` / ``entity_id`` — IDs + may be numeric like ``"12345"`` or opaque like ``"default-12345"``. + """ + + def test_returns_true_for_numeric_string(self): + self.assertTrue(event_id_normalizer.is_non_empty_string('12345')) + + def test_returns_true_for_opaque_string(self): + # Opaque IDs are explicitly valid for campaign_id / entity_id. + self.assertTrue(event_id_normalizer.is_non_empty_string('default-12345')) + self.assertTrue(event_id_normalizer.is_non_empty_string('layer_abc')) + self.assertTrue(event_id_normalizer.is_non_empty_string('abc')) + + def test_returns_true_for_whitespace_string(self): + # Whitespace is a non-empty string and so is accepted; + # character-content validation is deferred upstream. + self.assertTrue(event_id_normalizer.is_non_empty_string(' ')) + + def test_returns_false_for_empty_string(self): + self.assertFalse(event_id_normalizer.is_non_empty_string('')) + + def test_returns_false_for_none(self): + self.assertFalse(event_id_normalizer.is_non_empty_string(None)) + + def test_returns_false_for_non_string_types(self): + # Non-string types are rejected so the fallback path fires. + self.assertFalse(event_id_normalizer.is_non_empty_string(12345)) + self.assertFalse(event_id_normalizer.is_non_empty_string(123.0)) + self.assertFalse(event_id_normalizer.is_non_empty_string(True)) + self.assertFalse(event_id_normalizer.is_non_empty_string(['123'])) + self.assertFalse(event_id_normalizer.is_non_empty_string({'id': '123'})) + + +class IsNumericIdStringTest(unittest.TestCase): + """Cover :func:`event_id_normalizer.is_numeric_id_string` edge cases. + + Used only for ``variation_id``, which retains the strict + decimal-digit contract. + """ + + def test_returns_true_for_decimal_digit_string(self): + self.assertTrue(event_id_normalizer.is_numeric_id_string('12345')) + + def test_returns_true_for_single_digit(self): + self.assertTrue(event_id_normalizer.is_numeric_id_string('0')) + self.assertTrue(event_id_normalizer.is_numeric_id_string('9')) + + def test_returns_true_for_leading_zeros(self): + # Leading zeros are explicitly allowed. + self.assertTrue(event_id_normalizer.is_numeric_id_string('007')) + self.assertTrue(event_id_normalizer.is_numeric_id_string('00000')) + + def test_returns_false_for_empty_string(self): + self.assertFalse(event_id_normalizer.is_numeric_id_string('')) + + def test_returns_false_for_none(self): + self.assertFalse(event_id_normalizer.is_numeric_id_string(None)) + + def test_returns_false_for_int(self): + # The value must be a string. + self.assertFalse(event_id_normalizer.is_numeric_id_string(12345)) + self.assertFalse(event_id_normalizer.is_numeric_id_string(0)) + + def test_returns_false_for_float(self): + self.assertFalse(event_id_normalizer.is_numeric_id_string(123.0)) + + def test_returns_false_for_bool(self): + # ``bool`` is a subclass of ``int`` but is still not a ``str``. + self.assertFalse(event_id_normalizer.is_numeric_id_string(True)) + self.assertFalse(event_id_normalizer.is_numeric_id_string(False)) + + def test_returns_false_for_whitespace(self): + self.assertFalse(event_id_normalizer.is_numeric_id_string(' ')) + self.assertFalse(event_id_normalizer.is_numeric_id_string(' 123')) + self.assertFalse(event_id_normalizer.is_numeric_id_string('123 ')) + self.assertFalse(event_id_normalizer.is_numeric_id_string('1 2')) + self.assertFalse(event_id_normalizer.is_numeric_id_string('\t')) + self.assertFalse(event_id_normalizer.is_numeric_id_string('\n')) + + def test_returns_false_for_signed_numbers(self): + self.assertFalse(event_id_normalizer.is_numeric_id_string('-1')) + self.assertFalse(event_id_normalizer.is_numeric_id_string('+1')) + + def test_returns_false_for_decimals(self): + self.assertFalse(event_id_normalizer.is_numeric_id_string('1.0')) + self.assertFalse(event_id_normalizer.is_numeric_id_string('.5')) + + def test_returns_false_for_exponents(self): + self.assertFalse(event_id_normalizer.is_numeric_id_string('1e5')) + self.assertFalse(event_id_normalizer.is_numeric_id_string('1E5')) + + def test_returns_false_for_hex(self): + self.assertFalse(event_id_normalizer.is_numeric_id_string('0x1A')) + self.assertFalse(event_id_normalizer.is_numeric_id_string('abc')) + + def test_returns_false_for_unicode_digits(self): + # ``str.isdigit`` is True for many non-ASCII digit code points; the + # normalizer must reject these because the wire format expects ASCII. + self.assertFalse(event_id_normalizer.is_numeric_id_string('٠١')) # Arabic-Indic 01 + self.assertFalse(event_id_normalizer.is_numeric_id_string('²')) # superscript 2 + + def test_returns_false_for_collections(self): + self.assertFalse(event_id_normalizer.is_numeric_id_string(['123'])) + self.assertFalse(event_id_normalizer.is_numeric_id_string({'id': '123'})) + self.assertFalse(event_id_normalizer.is_numeric_id_string(('1',))) + + +class NormalizeCampaignIdTest(unittest.TestCase): + """Cover :func:`event_id_normalizer.normalize_campaign_id`. + + Any non-empty string is valid for campaign_id — fallback to + ``experiment_id`` fires only on empty/None/missing. + """ + + def test_returns_campaign_id_when_numeric(self): + self.assertEqual( + '111182', + event_id_normalizer.normalize_campaign_id('111182', '111127'), + ) + + def test_returns_campaign_id_when_opaque_string(self): + # Opaque IDs (e.g. holdout layer IDs) pass through. + self.assertEqual( + 'default-12345', + event_id_normalizer.normalize_campaign_id('default-12345', '111127'), + ) + self.assertEqual( + 'layer_abc', + event_id_normalizer.normalize_campaign_id('layer_abc', '111127'), + ) + + def test_returns_campaign_id_when_whitespace_string(self): + # Whitespace is non-empty; passes through (validation deferred upstream). + self.assertEqual( + ' ', + event_id_normalizer.normalize_campaign_id(' ', '111127'), + ) + + def test_falls_back_to_experiment_id_when_campaign_id_empty(self): + self.assertEqual( + '111127', + event_id_normalizer.normalize_campaign_id('', '111127'), + ) + + def test_falls_back_to_experiment_id_when_campaign_id_none(self): + self.assertEqual( + '111127', + event_id_normalizer.normalize_campaign_id(None, '111127'), + ) + + def test_falls_back_to_opaque_experiment_id(self): + # Both fields may be opaque non-numeric strings. + self.assertEqual( + 'exp_42', + event_id_normalizer.normalize_campaign_id('', 'exp_42'), + ) + + def test_returns_empty_string_when_both_empty_or_none(self): + # Do not drop / fail dispatch; return ''. + self.assertEqual('', event_id_normalizer.normalize_campaign_id(None, None)) + self.assertEqual('', event_id_normalizer.normalize_campaign_id('', '')) + self.assertEqual('', event_id_normalizer.normalize_campaign_id(None, '')) + + def test_preserves_leading_zeros(self): + self.assertEqual( + '007', + event_id_normalizer.normalize_campaign_id('007', '111127'), + ) + + +class NormalizeVariationIdTest(unittest.TestCase): + """Cover :func:`event_id_normalizer.normalize_variation_id`. + + ``variation_id`` retains the strict numeric-string contract. + """ + + def test_returns_variation_id_when_valid(self): + self.assertEqual( + '111129', + event_id_normalizer.normalize_variation_id('111129'), + ) + + def test_returns_none_when_empty(self): + self.assertIsNone(event_id_normalizer.normalize_variation_id('')) + + def test_returns_none_when_none(self): + self.assertIsNone(event_id_normalizer.normalize_variation_id(None)) + + def test_returns_none_when_non_string(self): + self.assertIsNone(event_id_normalizer.normalize_variation_id(111129)) + self.assertIsNone(event_id_normalizer.normalize_variation_id(123.0)) + self.assertIsNone(event_id_normalizer.normalize_variation_id(True)) + + def test_returns_none_when_non_numeric(self): + self.assertIsNone(event_id_normalizer.normalize_variation_id('variation_a')) + self.assertIsNone(event_id_normalizer.normalize_variation_id('abc')) + + def test_returns_none_when_whitespace(self): + self.assertIsNone(event_id_normalizer.normalize_variation_id(' ')) + self.assertIsNone(event_id_normalizer.normalize_variation_id(' 111129')) + + def test_returns_none_when_signed(self): + self.assertIsNone(event_id_normalizer.normalize_variation_id('-111129')) + + def test_preserves_leading_zeros(self): + self.assertEqual('007', event_id_normalizer.normalize_variation_id('007')) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_holdout_config.py b/tests/test_holdout_config.py index 6420e42c1..e9416e115 100644 --- a/tests/test_holdout_config.py +++ b/tests/test_holdout_config.py @@ -471,7 +471,7 @@ def test_local_holdouts_section_entries_excluded_from_global_list(self): self.assertEqual(config.get_global_holdouts(), []) def test_local_holdouts_missing_included_rules_logged_and_excluded(self): - """Entries in 'localHoldouts' without 'includedRules' are invalid per spec. + """Entries in 'localHoldouts' without 'includedRules' are invalid. SDK must log an error and exclude the entry from evaluation. It must NOT fall back to global application (the partition between sections is hard). From e1f2ec537d42df9af10d70105eac60a9aef7d45a Mon Sep 17 00:00:00 2001 From: Raju Ahmed Date: Thu, 2 Jul 2026 21:44:58 +0600 Subject: [PATCH 24/32] [AI-FSSDK] [FSSDK-12750] Use attribute id instead of key for CMAB prediction requests (#520) Co-authored-by: Farhan Anjum --- optimizely/cmab/cmab_service.py | 2 +- tests/test_cmab_service.py | 13 ++++++------- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/optimizely/cmab/cmab_service.py b/optimizely/cmab/cmab_service.py index 00e996ca5..081ecf512 100644 --- a/optimizely/cmab/cmab_service.py +++ b/optimizely/cmab/cmab_service.py @@ -163,7 +163,7 @@ def _filter_attributes(self, project_config: ProjectConfig, for attribute_id in cmab_attribute_ids: attribute = project_config.attribute_id_map.get(attribute_id) if attribute and attribute.key in user_attributes: - filtered_user_attributes[attribute.key] = user_attributes[attribute.key] + filtered_user_attributes[attribute.id] = user_attributes[attribute.key] return filtered_user_attributes diff --git a/tests/test_cmab_service.py b/tests/test_cmab_service.py index b26e277f7..deab77258 100644 --- a/tests/test_cmab_service.py +++ b/tests/test_cmab_service.py @@ -51,7 +51,7 @@ def setUp(self): def test_returns_decision_from_cache_when_valid(self): expected_key = self.cmab_service._get_cache_key("user123", "exp1") - expected_attributes = {"age": 25, "location": "USA"} + expected_attributes = {"66": 25, "77": "USA"} expected_hash = self.cmab_service._hash_attributes(expected_attributes) self.mock_cmab_cache.lookup.return_value = { @@ -70,7 +70,7 @@ def test_returns_decision_from_cache_when_valid(self): def test_ignores_cache_when_option_given(self): self.mock_cmab_client.fetch_decision.return_value = "varB" - expected_attributes = {"age": 25, "location": "USA"} + expected_attributes = {"66": 25, "77": "USA"} decision, _ = self.cmab_service.get_decision( self.mock_project_config, @@ -124,7 +124,7 @@ def test_new_decision_when_hash_changes(self): } self.mock_cmab_client.fetch_decision.return_value = "varE" - expected_attribute = {"age": 25, "location": "USA"} + expected_attribute = {"66": 25, "77": "USA"} expected_hash = self.cmab_service._hash_attributes(expected_attribute) expected_key = self.cmab_service._get_cache_key("user123", "exp1") @@ -148,8 +148,8 @@ def test_new_decision_when_hash_changes(self): def test_filter_attributes_returns_correct_subset(self): filtered = self.cmab_service._filter_attributes(self.mock_project_config, self.mock_user_context, "exp1") - self.assertEqual(filtered["age"], 25) - self.assertEqual(filtered["location"], "USA") + self.assertEqual(filtered["66"], 25) + self.assertEqual(filtered["77"], "USA") def test_filter_attributes_empty_when_no_cmab(self): self.mock_project_config.experiment_id_map["exp1"].cmab = None @@ -178,11 +178,10 @@ def test_only_cmab_attributes_passed_to_client(self): [OptimizelyDecideOption.IGNORE_CMAB_CACHE] ) - # Verify only age and location are passed (attributes configured in setUp) self.mock_cmab_client.fetch_decision.assert_called_once_with( "exp1", self.mock_user_context.user_id, - {"age": 25, "location": "USA"}, + {"66": 25, "77": "USA"}, decision["cmab_uuid"] ) From 3eaa6cb8dca7fc3c06ae0e97377ff64d6bb0a4dd Mon Sep 17 00:00:00 2001 From: Farhan Anjum Date: Fri, 10 Jul 2026 17:17:05 +0600 Subject: [PATCH 25/32] [FSSDK-12871] chore: preparing for release v5.6.0 (#521) --- CHANGELOG.md | 21 +++++++++++++++++++++ optimizely/version.py | 2 +- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 715ee3910..97d0f626a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,26 @@ # Optimizely Python SDK Changelog +## 5.6.0 +July 10th, 2026 + +### New Features + +#### **Local Holdouts Support** + +- Added local holdouts support to the Python SDK, enabling flag-level traffic exclusion from experiments. ([#512](https://github.com/optimizely/python-sdk/pull/512)) +- Added `localHoldouts` datafile section parsing for backward compatibility with older datafile formats. ([#517](https://github.com/optimizely/python-sdk/pull/517)) + +--- + +### Bug Fixes + +- Fixed invalid IDs in holdout decision events by normalizing `campaign_id`, `variation_id`, and `entity_id` fields. ([#518](https://github.com/optimizely/python-sdk/pull/518)) +- Fixed CMAB prediction requests to use attribute ID instead of attribute key. ([#520](https://github.com/optimizely/python-sdk/pull/520)) +- Fixed ODP identify events being sent with a single identifier, which is a no-op. ([#513](https://github.com/optimizely/python-sdk/pull/513)) + +--- + + ## 5.5.0 April 30th, 2026 diff --git a/optimizely/version.py b/optimizely/version.py index 85bb307e6..d9d9718e7 100644 --- a/optimizely/version.py +++ b/optimizely/version.py @@ -11,5 +11,5 @@ # See the License for the specific language governing permissions and # limitations under the License. -version_info = (5, 5, 0) +version_info = (5, 6, 0) __version__ = '.'.join(str(v) for v in version_info) From 16088706762d4d6a3e038b3df295dfc22651f192 Mon Sep 17 00:00:00 2001 From: esrakartalOpt <102107327+esrakartalOpt@users.noreply.github.com> Date: Wed, 5 Aug 2026 12:38:04 -0500 Subject: [PATCH 26/32] [AI-FSSDK] [FSSDK-12735] Add holdout exclusion logic for Targeted Delivery rules (#522) * [AI-FSSDK] [FSSDK-12735] Add holdout exclusion logic for Targeted Delivery rules * [AI-FSSDK] [FSSDK-12735] Add holdout event dispatch, local holdout flag isolation, and TD null passthrough * [AI-FSSDK] [FSSDK-12735] Fix holdout impression event tracking and add bypass decision reason * [FSSDK-12735] Re-trigger FSC tests after datafile updates * Fix message * [FSSDK-12735] Trigger FSC tests * Fix mypy no-redef error for result variable in decision_service Remove duplicate type annotation on second assignment to `result`, which was already typed on line 805. Co-Authored-By: Claude Opus 4.6 (1M context) --------- Co-authored-by: Farhan Anjum Co-authored-by: Claude Opus 4.6 (1M context) --- optimizely/decision_service.py | 68 +++-- optimizely/entities.py | 2 + optimizely/optimizely.py | 28 +- tests/test_decision_service_holdout.py | 382 +++++++++++++++++++++++++ tests/test_holdout_config.py | 31 ++ 5 files changed, 489 insertions(+), 22 deletions(-) diff --git a/optimizely/decision_service.py b/optimizely/decision_service.py index 111889084..b12352c2b 100644 --- a/optimizely/decision_service.py +++ b/optimizely/decision_service.py @@ -64,15 +64,11 @@ class VariationResult(TypedDict): variation: Optional[Union[entities.Variation, VariationDict]] -class DecisionResult(TypedDict): - """ - A TypedDict representing the result of a decision process. +class _DecisionResultOptional(TypedDict, total=False): + holdout_decision: Decision - Attributes: - decision (Decision): The decision object containing the outcome of the evaluation. - error (bool): Indicates whether an error occurred during the decision process. - reasons (List[str]): A list of reasons explaining the decision or any errors encountered. - """ + +class DecisionResult(_DecisionResultOptional): decision: Decision error: bool reasons: List[str] @@ -610,7 +606,6 @@ def get_variation_for_rollout( return Decision(experiment=rule, variation=forced_decision_variation, source=enums.DecisionSources.ROLLOUT, cmab_uuid=None), decide_reasons - # Check local holdouts targeting this specific delivery rule (FSSDK-12369) local_holdouts = project_config.get_holdouts_for_rule(rule.id) for holdout in local_holdouts: local_holdout_decision = self.get_variation_for_holdout( @@ -751,6 +746,9 @@ def get_decision_for_flag( reasons = decide_reasons.copy() if decide_reasons else [] user_id = user_context.user_id + global_holdout_result: DecisionResult | None = None + global_holdout_key: str | None = None + # Check global holdouts (flag level — before any rules are evaluated) global_holdouts = project_config.get_global_holdouts() for holdout in global_holdouts: @@ -758,7 +756,6 @@ def get_decision_for_flag( reasons.extend(holdout_decision['reasons']) decision = holdout_decision['decision'] - # Check if user was bucketed into holdout (has a variation) if decision.variation is None: continue @@ -768,18 +765,33 @@ def get_decision_for_flag( ) self.logger.info(message) reasons.append(message) - return { - 'decision': holdout_decision['decision'], - 'error': False, - 'reasons': reasons - } - # If no global holdout decision, check experiments then rollouts + if not holdout.exclude_targeted_deliveries: + return { + 'decision': holdout_decision['decision'], + 'error': False, + 'reasons': reasons + } + + message = ( + f"Holdout '{holdout.key}' excludes targeted deliveries. " + f"Targeted delivery rules will be evaluated." + ) + self.logger.info(message) + reasons.append(message) + global_holdout_result = holdout_decision + global_holdout_key = holdout.key + break + + # Check experiments then rollouts if feature_flag.experimentIds: for experiment_id in feature_flag.experimentIds: experiment = project_config.get_experiment_from_id(experiment_id) if experiment: + if global_holdout_result is not None and experiment.type != enums.ExperimentTypes.td: + continue + # Check for forced decision optimizely_decision_context = OptimizelyUserContext.OptimizelyDecisionContext( feature_flag.key, experiment.key) @@ -790,13 +802,15 @@ def get_decision_for_flag( if forced_decision_variation: decision = Decision(experiment, forced_decision_variation, enums.DecisionSources.FEATURE_TEST, None) - return { + result: DecisionResult = { 'decision': decision, 'error': False, 'reasons': reasons } + if global_holdout_result is not None: + result['holdout_decision'] = global_holdout_result['decision'] + return result - # Check local holdouts targeting this specific experiment rule (FSSDK-12369) local_holdouts = project_config.get_holdouts_for_rule(experiment.id) for holdout in local_holdouts: local_holdout_decision = self.get_variation_for_holdout( @@ -837,11 +851,22 @@ def get_decision_for_flag( decision = Decision(experiment, variation_result['variation'], enums.DecisionSources.FEATURE_TEST, variation_result['cmab_uuid']) - return { + result = { 'decision': decision, 'error': False, 'reasons': reasons } + if global_holdout_result is not None: + result['holdout_decision'] = global_holdout_result['decision'] + return result + + if global_holdout_result is not None: + message = ( + f"Holdout \"{global_holdout_key}\" has excludeTargetedDeliveries enabled, " + f"continuing to rollout evaluation." + ) + self.logger.info(message) + reasons.append(message) # If no experiment decision, check rollouts rollout_decision, rollout_reasons = self.get_variation_for_rollout( @@ -863,11 +888,14 @@ def get_decision_for_flag( else: self.logger.debug(f'User "{user_id}" not bucketed into any rollout for feature "{feature_flag.key}".') - return { + final_result: DecisionResult = { 'decision': rollout_decision, 'error': False, 'reasons': reasons } + if global_holdout_result is not None: + final_result['holdout_decision'] = global_holdout_result['decision'] + return final_result def get_variation_for_holdout( self, diff --git a/optimizely/entities.py b/optimizely/entities.py index 7b0b09e57..39caafe67 100644 --- a/optimizely/entities.py +++ b/optimizely/entities.py @@ -224,6 +224,7 @@ def __init__( audienceIds: list[str], audienceConditions: Optional[Sequence[str | list[str]]] = None, includedRules: Optional[list[str]] = None, + excludeTargetedDeliveries: bool = False, **kwargs: Any ): self.id = id @@ -236,6 +237,7 @@ def __init__( # Per-rule targeting for local holdouts. Scope comes from the datafile # section, not this field; ProjectConfig strips it on 'holdouts' entries. self.included_rules: Optional[list[str]] = includedRules + self.exclude_targeted_deliveries: bool = excludeTargetedDeliveries def get_audience_conditions_or_ids(self) -> Sequence[str | list[str]]: """Returns audienceConditions if present, otherwise audienceIds. diff --git a/optimizely/optimizely.py b/optimizely/optimizely.py index 04162823b..0f7c1da55 100644 --- a/optimizely/optimizely.py +++ b/optimizely/optimizely.py @@ -1245,7 +1245,8 @@ def _create_optimizely_decision( flag_decision: Decision, decision_reasons: Optional[list[str]], decide_options: list[str], - project_config: ProjectConfig + project_config: ProjectConfig, + holdout_decision: Optional[Decision] = None ) -> OptimizelyDecision: user_id = user_context.user_id feature_enabled = False @@ -1264,6 +1265,26 @@ def _create_optimizely_decision( feature_flag = project_config.feature_key_map.get(flag_key) + # Send holdout impression when user was bucketed into a holdout bypassed due to exclude_targeted_deliveries + if (holdout_decision is not None + and decision_source != DecisionSources.HOLDOUT + and OptimizelyDecideOption.DISABLE_DECISION_EVENT not in decide_options): + holdout_enabled = self._get_feature_enabled(holdout_decision.variation) + holdout_rule_key = holdout_decision.experiment.key if holdout_decision.experiment else '' + self._send_impression_event( + project_config, + holdout_decision.experiment, + holdout_decision.variation, + flag_key, + holdout_rule_key, + str(DecisionSources.HOLDOUT), + holdout_enabled, + user_id, + attributes, + holdout_decision.cmab_uuid + ) + decision_event_dispatched = True + # Send impression event if Decision came from a feature if OptimizelyDecideOption.DISABLE_DECISION_EVENT not in decide_options: if (decision_source == DecisionSources.FEATURE_TEST or @@ -1448,11 +1469,13 @@ def _decide_for_keys( user_context, merged_decide_options ) + holdout_decisions: dict[str, Optional[Decision]] = {} for i in range(0, len(flags_without_forced_decision)): decision = decision_list[i]['decision'] reasons = decision_list[i]['reasons'] error = decision_list[i]['error'] flag_key = flags_without_forced_decision[i].key + holdout_decisions[flag_key] = decision_list[i].get('holdout_decision') # store error decision against key and remove key from valid keys if error: optimizely_decision = OptimizelyDecision.new_error_decision(flags_without_forced_decision[i].key, @@ -1472,7 +1495,8 @@ def _decide_for_keys( flag_decision, decision_reasons, merged_decide_options, - project_config + project_config, + holdout_decision=holdout_decisions.get(key) ) enabled_flags_only_missing = OptimizelyDecideOption.ENABLED_FLAGS_ONLY not in merged_decide_options is_enabled = optimizely_decision.enabled diff --git a/tests/test_decision_service_holdout.py b/tests/test_decision_service_holdout.py index 21a269b2a..da85ae4e4 100644 --- a/tests/test_decision_service_holdout.py +++ b/tests/test_decision_service_holdout.py @@ -1708,3 +1708,385 @@ def test_no_holdouts_at_all_falls_through_to_experiment(self): self.assertIsNotNone(result) decision = result['decision'] self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) + + +# --------------------------------------------------------------------------- +# Exclude Targeted Deliveries Tests +# --------------------------------------------------------------------------- + +def _holdout_with_etd(holdout_id, key, exclude_targeted_deliveries=False, + included_rules=None, traffic=None, status='Running'): + """Build a holdout dict with excludeTargetedDeliveries field.""" + h = { + 'id': holdout_id, + 'key': key, + 'status': status, + 'audienceIds': [], + 'variations': _HOLDOUT_VARIATION, + 'trafficAllocation': traffic or _FULL_TRAFFIC, + 'excludeTargetedDeliveries': exclude_targeted_deliveries, + } + if included_rules is not None: + h['includedRules'] = included_rules + return h + + +class ExcludeTargetedDeliveriesTest(base.BaseTest): + """Tests for exclude_targeted_deliveries behavior on holdouts. + + When a holdout has exclude_targeted_deliveries=True: + - TD (targeted delivery) experiments should bypass the holdout + - A/B and other experiment types should still be blocked by the holdout + - Delivery (rollout) rules should bypass local holdouts with this flag + """ + + def setUp(self): + base.BaseTest.setUp(self) + self.error_handler = error_handler.NoOpErrorHandler() + self.spy_logger = mock.MagicMock(spec=logger.SimpleLogger) + self.spy_logger.logger = self.spy_logger + self.spy_user_profile_service = mock.MagicMock() + self.spy_cmab_service = mock.MagicMock() + + def tearDown(self): + if hasattr(self, 'opt_obj'): + self.opt_obj.close() + + def _make_opt_with_td(self, holdouts, local_holdouts=None, experiment_type=None): + """Build Optimizely instance, optionally setting type on experiment '111127'.""" + cfg = self.config_dict_with_features.copy() + + if experiment_type is not None: + experiments = [] + for exp in cfg['experiments']: + exp_copy = exp.copy() + if exp_copy['id'] == '111127': + exp_copy['type'] = experiment_type + experiments.append(exp_copy) + cfg['experiments'] = experiments + + if local_holdouts is None: + globals_list: list = [] + locals_list: list = [] + for h in holdouts: + if h.get('includedRules') is not None: + locals_list.append(h) + else: + globals_list.append(h) + cfg['holdouts'] = globals_list + if locals_list: + cfg['localHoldouts'] = locals_list + else: + cfg['holdouts'] = holdouts + cfg['localHoldouts'] = local_holdouts + + self.opt_obj = optimizely_module.Optimizely(json.dumps(cfg)) + return self.opt_obj + + def _decision_svc(self): + return decision_service.DecisionService( + self.spy_logger, + self.spy_user_profile_service, + self.spy_cmab_service, + ) + + # ------------------------------------------------------------------ + # Test 1: Global holdout with exclude_targeted_deliveries=False (default) + # ------------------------------------------------------------------ + + def test_global_holdout_exclude_td_false_blocks_all_rules(self): + """Global holdout with exclude_targeted_deliveries=False blocks all rules as before.""" + opt = self._make_opt_with_td( + [_holdout_with_etd('gh1', 'global_no_exclude', exclude_targeted_deliveries=False)], + experiment_type='td', + ) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + + ds = self._decision_svc() + + with mock.patch.object(ds, 'get_variation', wraps=ds.get_variation) as mock_get_var: + user_ctx = opt.create_user_context('user_blocked', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + decision = result['decision'] + self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) + mock_get_var.assert_not_called() + + # ------------------------------------------------------------------ + # Test 2: Global holdout with exclude_targeted_deliveries=True, TD experiment + # ------------------------------------------------------------------ + + def test_global_holdout_exclude_td_true_allows_td_experiment(self): + """Global holdout with exclude_targeted_deliveries=True allows TD rules through.""" + opt = self._make_opt_with_td( + [_holdout_with_etd('gh1', 'global_exclude_td', exclude_targeted_deliveries=True)], + experiment_type='td', + ) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + + ds = self._decision_svc() + user_ctx = opt.create_user_context('testUserId', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + decision = result['decision'] + # TD experiment should be evaluated, not blocked by holdout + self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) + + # ------------------------------------------------------------------ + # Test 3: Global holdout with exclude_targeted_deliveries=True, A/B experiment + # ------------------------------------------------------------------ + + def test_global_holdout_exclude_td_true_blocks_ab_experiment(self): + """Global holdout with exclude_targeted_deliveries=True still blocks A/B rules. + The A/B experiment is skipped and a non-holdout decision is returned, + with the holdout decision attached separately.""" + opt = self._make_opt_with_td( + [_holdout_with_etd('gh1', 'global_exclude_td', exclude_targeted_deliveries=True)], + experiment_type='ab', + ) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + + ds = self._decision_svc() + + with mock.patch.object(ds, 'get_variation', wraps=ds.get_variation) as mock_get_var: + user_ctx = opt.create_user_context('user_blocked_ab', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + decision = result['decision'] + self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) + mock_get_var.assert_not_called() + self.assertIsNotNone(result.get('holdout_decision')) + + # ------------------------------------------------------------------ + # Test 4: Global holdout with exclude_targeted_deliveries=True, no TD matches + # ------------------------------------------------------------------ + + def test_global_holdout_exclude_td_true_no_td_returns_non_holdout_decision(self): + """When exclude_targeted_deliveries=True but no TD experiments match, + returns a non-holdout decision with the bypassed holdout attached + and includes the rollout evaluation reason.""" + opt = self._make_opt_with_td( + [_holdout_with_etd('gh1', 'global_exclude_td', exclude_targeted_deliveries=True)], + ) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + + ds = self._decision_svc() + user_ctx = opt.create_user_context('user_no_td', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + decision = result['decision'] + self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) + self.assertIsNotNone(result.get('holdout_decision')) + + expected_reason = ( + "Holdout \"global_exclude_td\" has excludeTargetedDeliveries enabled, " + "continuing to rollout evaluation." + ) + self.assertIn(expected_reason, result['reasons']) + + # ------------------------------------------------------------------ + # Test 5: Local holdout on delivery rule with exclude_targeted_deliveries=True + # ------------------------------------------------------------------ + + def test_local_holdout_delivery_rule_exclude_td_true_still_applies(self): + """Local holdout on delivery rule with exclude_targeted_deliveries=True + still applies because local holdouts ignore that flag.""" + delivery_rule_id = '211147' + opt = self._make_opt_with_td( + [_holdout_with_etd( + 'lh1', 'local_delivery_exclude', + exclude_targeted_deliveries=True, + included_rules=[delivery_rule_id], + )], + ) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_rollout') + + ds = self._decision_svc() + user_ctx = opt.create_user_context('user_delivery_exclude', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + decision = result['decision'] + self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) + + # ------------------------------------------------------------------ + # Test 6: Local holdout on experiment rule (TD type) with exclude_targeted_deliveries=True + # ------------------------------------------------------------------ + + def test_local_holdout_td_experiment_exclude_td_true_still_applies(self): + """Local holdout on TD experiment with exclude_targeted_deliveries=True + still applies because local holdouts ignore that flag.""" + experiment_rule_id = '111127' + opt = self._make_opt_with_td( + [_holdout_with_etd( + 'lh1', 'local_td_exclude', + exclude_targeted_deliveries=True, + included_rules=[experiment_rule_id], + )], + experiment_type='td', + ) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + + ds = self._decision_svc() + user_ctx = opt.create_user_context('testUserId', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + decision = result['decision'] + self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) + + # ------------------------------------------------------------------ + # Test 7: Local holdout on experiment rule (A/B type) with exclude_targeted_deliveries=True + # ------------------------------------------------------------------ + + def test_local_holdout_ab_experiment_exclude_td_true_still_applies(self): + """Local holdout on A/B experiment with exclude_targeted_deliveries=True + still applies the holdout (A/B is not a targeted delivery).""" + experiment_rule_id = '111127' + opt = self._make_opt_with_td( + [_holdout_with_etd( + 'lh1', 'local_ab_exclude', + exclude_targeted_deliveries=True, + included_rules=[experiment_rule_id], + )], + experiment_type='ab', + ) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + + ds = self._decision_svc() + + with mock.patch.object(ds, 'get_variation', wraps=ds.get_variation) as mock_get_var: + user_ctx = opt.create_user_context('user_ab_holdout', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + decision = result['decision'] + # A/B experiment should still be blocked by local holdout + self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) + mock_get_var.assert_not_called() + + # ------------------------------------------------------------------ + # Test 8: Missing field (backward compatibility) + # ------------------------------------------------------------------ + + def test_missing_exclude_td_field_defaults_to_false(self): + """When excludeTargetedDeliveries is not in the datafile, defaults to False + and holdout works as before (blocks all rules).""" + # Use _holdout helper which does NOT set excludeTargetedDeliveries + opt = self._make_opt_with_td( + [_holdout('gh1', 'legacy_holdout', traffic=_FULL_TRAFFIC)], + experiment_type='td', + ) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + + ds = self._decision_svc() + user_ctx = opt.create_user_context('user_legacy', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + decision = result['decision'] + # Without the field, holdout should block all rules including TD + self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) + + # Verify entity defaults + holdout = config.holdouts[0] if config.holdouts else None + self.assertIsNotNone(holdout) + self.assertFalse(holdout.exclude_targeted_deliveries) + + # ------------------------------------------------------------------ + # Test 9: TD match returns holdout_decision in result + # ------------------------------------------------------------------ + + def test_global_holdout_exclude_td_true_td_match_has_holdout_decision(self): + """When exclude_targeted_deliveries=True and a TD experiment matches, + the result contains holdout_decision with the bypassed holdout.""" + opt = self._make_opt_with_td( + [_holdout_with_etd('gh1', 'global_exclude_td', exclude_targeted_deliveries=True)], + experiment_type='td', + ) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + + ds = self._decision_svc() + user_ctx = opt.create_user_context('testUserId', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + decision = result['decision'] + self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) + self.assertIsNotNone(result.get('holdout_decision')) + self.assertEqual(result['holdout_decision'].source, enums.DecisionSources.HOLDOUT) + + # ------------------------------------------------------------------ + # Test 10: No TD match returns non-holdout with holdout_decision attached + # ------------------------------------------------------------------ + + def test_global_holdout_exclude_td_true_no_td_has_holdout_decision(self): + """When exclude_targeted_deliveries=True and no TD matches, + result is non-holdout but holdout_decision key is present, + and reasons include the rollout evaluation continuation message.""" + opt = self._make_opt_with_td( + [_holdout_with_etd('gh1', 'global_exclude_td', exclude_targeted_deliveries=True)], + ) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + + ds = self._decision_svc() + user_ctx = opt.create_user_context('user_no_td', {}) + result = ds.get_decision_for_flag(feature_flag, user_ctx, config) + + decision = result['decision'] + self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) + holdout_dec = result.get('holdout_decision') + self.assertIsNotNone(holdout_dec) + self.assertEqual(holdout_dec.source, enums.DecisionSources.HOLDOUT) + + expected_reason = ( + "Holdout \"global_exclude_td\" has excludeTargetedDeliveries enabled, " + "continuing to rollout evaluation." + ) + self.assertIn(expected_reason, result['reasons']) + + # ------------------------------------------------------------------ + # Test 11: Holdout impression event dispatched for bypassed holdout + # ------------------------------------------------------------------ + + def test_holdout_impression_sent_when_td_evaluated(self): + """When exclude_targeted_deliveries=True and TD matches, + two impression events are sent: one for holdout, one for TD, + and decision_event_dispatched is True in notification.""" + opt = self._make_opt_with_td( + [_holdout_with_etd('gh1', 'global_exclude_td', exclude_targeted_deliveries=True)], + experiment_type='td', + ) + + captured_notifications: list[dict[str, object]] = [] + + def capture_notification(notification_type: str, user_id: str, + user_attributes: dict[str, object], + decision_info: dict[str, object]) -> None: + captured_notifications.append(decision_info.copy()) + + opt.notification_center.add_notification_listener( + enums.NotificationTypes.DECISION, + capture_notification + ) + + with mock.patch.object(opt, '_send_impression_event', wraps=opt._send_impression_event) as mock_send: + user_ctx = opt.create_user_context('testUserId', {}) + user_ctx.decide('test_feature_in_experiment') + + self.assertEqual(mock_send.call_count, 2) + call_rule_types = [call.args[5] if len(call.args) > 5 else call.kwargs.get('rule_type') + for call in mock_send.call_args_list] + self.assertIn(str(enums.DecisionSources.HOLDOUT), call_rule_types) + self.assertIn(str(enums.DecisionSources.FEATURE_TEST), call_rule_types) + + self.assertEqual(len(captured_notifications), 1) + self.assertTrue( + captured_notifications[0].get('decision_event_dispatched'), + 'decision_event_dispatched should be True when holdout impression is sent' + ) diff --git a/tests/test_holdout_config.py b/tests/test_holdout_config.py index e9416e115..074f4cdeb 100644 --- a/tests/test_holdout_config.py +++ b/tests/test_holdout_config.py @@ -427,6 +427,37 @@ def test_is_global_entity_property_independent_of_section(self): self.assertFalse(h_empty.is_global) +class HoldoutEntityExcludeTargetedDeliveriesTest(unittest.TestCase): + """Tests for the Holdout.exclude_targeted_deliveries field storage.""" + + def test_exclude_targeted_deliveries_stored_true(self): + """exclude_targeted_deliveries=True should be stored correctly.""" + holdout = entities.Holdout( + id='h1', key='etd_holdout', status='Running', + variations=HOLDOUT_VARIATION, trafficAllocation=FULL_TRAFFIC, + audienceIds=[], excludeTargetedDeliveries=True, + ) + self.assertTrue(holdout.exclude_targeted_deliveries) + + def test_exclude_targeted_deliveries_stored_false(self): + """exclude_targeted_deliveries=False should be stored correctly.""" + holdout = entities.Holdout( + id='h1', key='etd_holdout', status='Running', + variations=HOLDOUT_VARIATION, trafficAllocation=FULL_TRAFFIC, + audienceIds=[], excludeTargetedDeliveries=False, + ) + self.assertFalse(holdout.exclude_targeted_deliveries) + + def test_exclude_targeted_deliveries_defaults_to_false(self): + """When not provided, exclude_targeted_deliveries defaults to False.""" + holdout = entities.Holdout( + id='h1', key='default_holdout', status='Running', + variations=HOLDOUT_VARIATION, trafficAllocation=FULL_TRAFFIC, + audienceIds=[], + ) + self.assertFalse(holdout.exclude_targeted_deliveries) + + class LocalHoldoutsSectionTest(unittest.TestCase): """Tests for the new top-level 'localHoldouts' datafile section (FSSDK-12760). From 2dc0ac188284935e829c44b3b6b6ccb8a7e947c2 Mon Sep 17 00:00:00 2001 From: Md Junaed Hossain <169046794+junaed-optimizely@users.noreply.github.com> Date: Mon, 7 Sep 2026 17:05:07 +0600 Subject: [PATCH 27/32] [AI-FSSDK] [FSSDK-13070] prepare for release python v5.7.0 (#523) * [FSSDK-13070] update CHANGELOG for python v5.7.0 * [FSSDK-13070] bump version to 5.7.0 --- CHANGELOG.md | 11 +++++++++++ optimizely/version.py | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 97d0f626a..8f36a597e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Optimizely Python SDK Changelog +## 5.7.0 +September 2nd, 2026 + +### New Features + +**Holdout Targeted Delivery Exclusion**: Holdouts can now be configured to exclude Targeted Delivery rules, so users held out of experiments still receive their Targeted Delivery experiences. This gives you a cleaner measure of experiment impact without holding users back from ongoing rollouts. + +- Add holdout exclusion logic for Targeted Delivery rules ([#522](https://github.com/optimizely/python-sdk/pull/522)) + +--- + ## 5.6.0 July 10th, 2026 diff --git a/optimizely/version.py b/optimizely/version.py index d9d9718e7..88def8194 100644 --- a/optimizely/version.py +++ b/optimizely/version.py @@ -11,5 +11,5 @@ # See the License for the specific language governing permissions and # limitations under the License. -version_info = (5, 6, 0) +version_info = (5, 7, 0) __version__ = '.'.join(str(v) for v in version_info) From eff999b4d461b09c267e131a789b9f142666985d Mon Sep 17 00:00:00 2001 From: Farhan Anjum Date: Mon, 26 Oct 2026 20:24:54 +0600 Subject: [PATCH 28/32] [FSSDK-13300] Remove dead Python 3.7 typing guards (#526) * [FSSDK-13300] Remove dead Python 3.7 typing guards and pin mypy mypy 2.4.0 rejects the `if version_info < (3, 8)` conditional Protocol imports, failing type-check on every PR. Those branches only run on Python 3.7, which has been unsupported since 5.0, so import Final, Literal, Protocol and TypedDict directly from typing. Drop the mypy.ini unused-ignore override that existed only for the old TypedDict import, and pin mypy~=2.4.0 so new mypy releases can't break CI unannounced. Co-Authored-By: Claude Opus 5.5 * [FSSDK-13300] Leave mypy unpinned Keep requirements/typing.txt as on master. The typing import cleanup alone fixes the mypy 2.4.0 failure. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- mypy.ini | 4 ---- optimizely/bucketer.py | 9 +-------- optimizely/decision/optimizely_decide_option.py | 7 +------ .../decision/optimizely_decision_message.py | 7 +------ optimizely/entities.py | 8 +------- optimizely/event/event_factory.py | 8 +------- optimizely/event/event_processor.py | 9 +-------- optimizely/event/log_event.py | 9 +-------- optimizely/event/user_event.py | 9 +-------- optimizely/event_builder.py | 8 +------- optimizely/event_dispatcher.py | 7 +------ optimizely/helpers/condition.py | 9 +-------- optimizely/helpers/enums.py | 7 +------ optimizely/helpers/event_tag_utils.py | 8 +------- optimizely/helpers/types.py | 9 +-------- optimizely/logger.py | 8 +------- optimizely/notification_center.py | 8 +------- optimizely/odp/lru_cache.py | 8 +------- optimizely/odp/optimizely_odp_option.py | 7 +------ optimizely/project_config.py | 8 +------- optimizely/user_profile.py | 16 +++++----------- 21 files changed, 24 insertions(+), 149 deletions(-) diff --git a/mypy.ini b/mypy.ini index 5de83593c..8d7ecd550 100644 --- a/mypy.ini +++ b/mypy.ini @@ -9,7 +9,3 @@ exclude = (?x)( ) show_error_codes = True pretty = True - -# suppress error on conditional import of typing_extensions module -[mypy-optimizely.helpers.types] -no_warn_unused_ignores = True diff --git a/optimizely/bucketer.py b/optimizely/bucketer.py index d1e0b047c..e21fb865e 100644 --- a/optimizely/bucketer.py +++ b/optimizely/bucketer.py @@ -12,19 +12,12 @@ # limitations under the License. from __future__ import annotations -from typing import Optional, TYPE_CHECKING, cast +from typing import Optional, TYPE_CHECKING, cast, Final import math -from sys import version_info from .lib import pymmh3 as mmh3 -if version_info < (3, 8): - from typing_extensions import Final -else: - from typing import Final - - if TYPE_CHECKING: # prevent circular dependenacy by skipping import at runtime from .project_config import ProjectConfig diff --git a/optimizely/decision/optimizely_decide_option.py b/optimizely/decision/optimizely_decide_option.py index 0443ddef4..7e5e43505 100644 --- a/optimizely/decision/optimizely_decide_option.py +++ b/optimizely/decision/optimizely_decide_option.py @@ -11,12 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from sys import version_info - -if version_info < (3, 8): - from typing_extensions import Final -else: - from typing import Final +from typing import Final class OptimizelyDecideOption: diff --git a/optimizely/decision/optimizely_decision_message.py b/optimizely/decision/optimizely_decision_message.py index c61783225..27112d8ff 100644 --- a/optimizely/decision/optimizely_decision_message.py +++ b/optimizely/decision/optimizely_decision_message.py @@ -11,12 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from sys import version_info - -if version_info < (3, 8): - from typing_extensions import Final -else: - from typing import Final +from typing import Final class OptimizelyDecisionMessage: diff --git a/optimizely/entities.py b/optimizely/entities.py index 39caafe67..b928141c2 100644 --- a/optimizely/entities.py +++ b/optimizely/entities.py @@ -11,13 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations -from typing import TYPE_CHECKING, Any, Optional, Sequence -from sys import version_info - -if version_info < (3, 8): - from typing_extensions import Final -else: - from typing import Final +from typing import TYPE_CHECKING, Any, Optional, Sequence, Final if TYPE_CHECKING: diff --git a/optimizely/event/event_factory.py b/optimizely/event/event_factory.py index b6a9c02ae..34bc04e2f 100644 --- a/optimizely/event/event_factory.py +++ b/optimizely/event/event_factory.py @@ -12,8 +12,7 @@ # limitations under the License. from __future__ import annotations -from typing import TYPE_CHECKING, Optional, Sequence, cast, List -from sys import version_info +from typing import TYPE_CHECKING, Optional, Sequence, cast, List, Final from optimizely import entities from optimizely.helpers import enums from optimizely.helpers import event_tag_utils @@ -23,11 +22,6 @@ from . import payload from . import user_event -if version_info < (3, 8): - from typing_extensions import Final -else: - from typing import Final - if TYPE_CHECKING: # prevent circular dependenacy by skipping import at runtime from optimizely.project_config import ProjectConfig diff --git a/optimizely/event/event_processor.py b/optimizely/event/event_processor.py index bdce6d9da..0d0211d04 100644 --- a/optimizely/event/event_processor.py +++ b/optimizely/event/event_processor.py @@ -17,10 +17,9 @@ import threading import time -from typing import Optional +from typing import Optional, Final from datetime import timedelta import queue -from sys import version_info from optimizely import logger as _logging from optimizely import notification_center as _notification_center @@ -31,12 +30,6 @@ from .user_event import UserEvent -if version_info < (3, 8): - from typing_extensions import Final -else: - from typing import Final - - class BaseEventProcessor(ABC): """ Class encapsulating event processing. Override with your own implementation. """ diff --git a/optimizely/event/log_event.py b/optimizely/event/log_event.py index 49c344dd8..568c2cefd 100644 --- a/optimizely/event/log_event.py +++ b/optimizely/event/log_event.py @@ -12,17 +12,10 @@ # limitations under the License. from __future__ import annotations -from typing import Optional, Any -from sys import version_info +from typing import Optional, Any, Literal from optimizely import event_builder -if version_info < (3, 8): - from typing_extensions import Literal -else: - from typing import Literal - - class LogEvent(event_builder.Event): """ Representation of an event which can be sent to Optimizely events API. """ diff --git a/optimizely/event/user_event.py b/optimizely/event/user_event.py index 8006c052e..a2cb2df70 100644 --- a/optimizely/event/user_event.py +++ b/optimizely/event/user_event.py @@ -13,18 +13,11 @@ from __future__ import annotations import time import uuid -from typing import TYPE_CHECKING, Optional -from sys import version_info +from typing import TYPE_CHECKING, Optional, Final from optimizely import version -if version_info < (3, 8): - from typing_extensions import Final -else: - from typing import Final - - if TYPE_CHECKING: # prevent circular dependenacy by skipping import at runtime from optimizely.entities import Experiment, Variation, Event, Holdout diff --git a/optimizely/event_builder.py b/optimizely/event_builder.py index 7ef6b347a..67169d2a8 100644 --- a/optimizely/event_builder.py +++ b/optimizely/event_builder.py @@ -13,9 +13,8 @@ from __future__ import annotations import time -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any, Optional, Final, Literal import uuid -from sys import version_info from . import version from .event import event_id_normalizer @@ -23,11 +22,6 @@ from .helpers import event_tag_utils from .helpers import validator -if version_info < (3, 8): - from typing_extensions import Final, Literal -else: - from typing import Final, Literal - if TYPE_CHECKING: # prevent circular dependenacy by skipping import at runtime from .entities import Experiment diff --git a/optimizely/event_dispatcher.py b/optimizely/event_dispatcher.py index b06b9e187..cf4683401 100644 --- a/optimizely/event_dispatcher.py +++ b/optimizely/event_dispatcher.py @@ -13,7 +13,7 @@ import json import logging -from sys import version_info +from typing import Protocol import requests from requests import exceptions as request_exception @@ -23,11 +23,6 @@ from . import event_builder from .helpers.enums import HTTPVerbs, EventDispatchConfig -if version_info < (3, 8): - from typing_extensions import Protocol -else: - from typing import Protocol - class CustomEventDispatcher(Protocol): """Interface for a custom event dispatcher and required method `dispatch_event`. """ diff --git a/optimizely/helpers/condition.py b/optimizely/helpers/condition.py index 40338b407..48f097d99 100644 --- a/optimizely/helpers/condition.py +++ b/optimizely/helpers/condition.py @@ -14,8 +14,7 @@ from __future__ import annotations import json import numbers -from typing import TYPE_CHECKING, Any, Callable, Optional -from sys import version_info +from typing import TYPE_CHECKING, Any, Callable, Optional, Literal, Final from . import validator from optimizely import optimizely_user_context @@ -29,12 +28,6 @@ from optimizely.logger import Logger -if version_info < (3, 8): - from typing_extensions import Literal, Final -else: - from typing import Literal, Final - - class ConditionOperatorTypes: AND: Final = 'and' OR: Final = 'or' diff --git a/optimizely/helpers/enums.py b/optimizely/helpers/enums.py index 2d1d46764..0e4eb3168 100644 --- a/optimizely/helpers/enums.py +++ b/optimizely/helpers/enums.py @@ -12,12 +12,7 @@ # limitations under the License. import logging -from sys import version_info - -if version_info < (3, 8): - from typing_extensions import Final -else: - from typing import Final +from typing import Final class CommonAudienceEvaluationLogs: diff --git a/optimizely/helpers/event_tag_utils.py b/optimizely/helpers/event_tag_utils.py index ad90cc132..618259508 100644 --- a/optimizely/helpers/event_tag_utils.py +++ b/optimizely/helpers/event_tag_utils.py @@ -12,16 +12,10 @@ # limitations under the License. from __future__ import annotations -from typing import TYPE_CHECKING, Any, Optional, NewType, Dict +from typing import TYPE_CHECKING, Any, Optional, NewType, Dict, Final from . import enums import math import numbers -from sys import version_info - -if version_info < (3, 8): - from typing_extensions import Final -else: - from typing import Final if TYPE_CHECKING: diff --git a/optimizely/helpers/types.py b/optimizely/helpers/types.py index 7b65ab134..2d8ba7d4f 100644 --- a/optimizely/helpers/types.py +++ b/optimizely/helpers/types.py @@ -12,14 +12,7 @@ # limitations under the License. from __future__ import annotations -from typing import Literal, Optional, Any -from sys import version_info - - -if version_info < (3, 8): - from typing_extensions import TypedDict -else: - from typing import TypedDict # type: ignore +from typing import Literal, Optional, Any, TypedDict # Intermediate types for type checking deserialized datafile json before actual class instantiation. diff --git a/optimizely/logger.py b/optimizely/logger.py index 42f879de6..c50b36940 100644 --- a/optimizely/logger.py +++ b/optimizely/logger.py @@ -11,17 +11,11 @@ # See the License for the specific language governing permissions and # limitations under the License. import logging -from typing import Any, Optional, Union +from typing import Any, Optional, Union, Final import warnings -from sys import version_info from .helpers import enums -if version_info < (3, 8): - from typing_extensions import Final -else: - from typing import Final - _DEFAULT_LOG_FORMAT: Final = '%(levelname)-8s %(asctime)s %(filename)s:%(lineno)s:%(message)s' diff --git a/optimizely/notification_center.py b/optimizely/notification_center.py index 3d0b0cba3..b6b89ffda 100644 --- a/optimizely/notification_center.py +++ b/optimizely/notification_center.py @@ -12,15 +12,9 @@ # limitations under the License. from __future__ import annotations -from typing import Any, Callable, Optional +from typing import Any, Callable, Optional, Final from .helpers import enums from . import logger as optimizely_logger -from sys import version_info - -if version_info < (3, 8): - from typing_extensions import Final -else: - from typing import Final NOTIFICATION_TYPES: Final = tuple( diff --git a/optimizely/odp/lru_cache.py b/optimizely/odp/lru_cache.py index 64337dadd..55d62a948 100644 --- a/optimizely/odp/lru_cache.py +++ b/optimizely/odp/lru_cache.py @@ -16,13 +16,7 @@ import threading from time import time from collections import OrderedDict -from typing import Optional, Generic, TypeVar, Hashable -from sys import version_info - -if version_info < (3, 8): - from typing_extensions import Protocol -else: - from typing import Protocol +from typing import Optional, Generic, TypeVar, Hashable, Protocol # generic type definitions for LRUCache parameters K = TypeVar('K', bound=Hashable, contravariant=True) diff --git a/optimizely/odp/optimizely_odp_option.py b/optimizely/odp/optimizely_odp_option.py index 94e1e90e4..62163fd76 100644 --- a/optimizely/odp/optimizely_odp_option.py +++ b/optimizely/odp/optimizely_odp_option.py @@ -11,12 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from sys import version_info - -if version_info < (3, 8): - from typing_extensions import Final -else: - from typing import Final +from typing import Final class OptimizelyOdpOption: diff --git a/optimizely/project_config.py b/optimizely/project_config.py index a7152ae83..3cbf730e3 100644 --- a/optimizely/project_config.py +++ b/optimizely/project_config.py @@ -12,8 +12,7 @@ # limitations under the License. from __future__ import annotations import json -from typing import TYPE_CHECKING, Optional, Type, TypeVar, Union, cast, Any, Iterable, List -from sys import version_info +from typing import TYPE_CHECKING, Optional, Type, TypeVar, Union, cast, Any, Iterable, List, Final from . import entities from . import exceptions @@ -21,11 +20,6 @@ from .helpers import enums from .helpers import types -if version_info < (3, 8): - from typing_extensions import Final -else: - from typing import Final - if TYPE_CHECKING: # prevent circular dependenacy by skipping import at runtime from .logger import Logger diff --git a/optimizely/user_profile.py b/optimizely/user_profile.py index e3a56195c..591df5eac 100644 --- a/optimizely/user_profile.py +++ b/optimizely/user_profile.py @@ -12,19 +12,13 @@ # limitations under the License. from __future__ import annotations -from typing import Any, Optional -from sys import version_info +from typing import Any, Optional, Final, TYPE_CHECKING from . import logger as _logging -if version_info < (3, 8): - from typing_extensions import Final -else: - from typing import Final, TYPE_CHECKING - - if TYPE_CHECKING: - # prevent circular dependenacy by skipping import at runtime - from .entities import Experiment, Variation - from optimizely.error_handler import BaseErrorHandler +if TYPE_CHECKING: + # prevent circular dependenacy by skipping import at runtime + from .entities import Experiment, Variation + from optimizely.error_handler import BaseErrorHandler class UserProfile: From 3732db68c6310fab6f679c11bd23f14faf3b216c Mon Sep 17 00:00:00 2001 From: Alex Yong <96444887+alexjoeyyong@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:03:32 -0400 Subject: [PATCH 29/32] [AI-FSSDK] [FSSDK-12958] Continue rule evaluation after local holdout hit (#525) * [AI-FSSDK] [FSSDK-12958] Continue rule evaluation after local holdout hit * [AI-FSSDK] [FSSDK-12958] Add tests for disabled decision events and two experiment rules * [AI-FSSDK] [FSSDK-12958] Add test for one local holdout hit on two rules * [AI-FSSDK] [FSSDK-12958] Keep deprecated holdout_decision key alongside list * [AI-FSSDK] [FSSDK-12958] Add test for holdout hit then CMAB decision error * [AI-FSSDK] [FSSDK-12958] Re-run CI --------- Co-authored-by: Farhan Anjum --- optimizely/decision_service.py | 104 +++++---- optimizely/optimizely.py | 43 ++-- tests/test_decision_service.py | 4 +- tests/test_decision_service_holdout.py | 290 ++++++++++++++++++++++--- 4 files changed, 345 insertions(+), 96 deletions(-) diff --git a/optimizely/decision_service.py b/optimizely/decision_service.py index b12352c2b..c5044511f 100644 --- a/optimizely/decision_service.py +++ b/optimizely/decision_service.py @@ -1,4 +1,4 @@ -# Copyright 2017-2022, Optimizely +# Copyright 2017-2022, 2026, Optimizely # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -65,7 +65,8 @@ class VariationResult(TypedDict): class _DecisionResultOptional(TypedDict, total=False): - holdout_decision: Decision + holdout_decision: Decision # Deprecated: first entry of holdout_decisions. + holdout_decisions: List[Decision] class DecisionResult(_DecisionResultOptional): @@ -552,7 +553,11 @@ def get_variation( } def get_variation_for_rollout( - self, project_config: ProjectConfig, feature: entities.FeatureFlag, user_context: OptimizelyUserContext + self, + project_config: ProjectConfig, + feature: entities.FeatureFlag, + user_context: OptimizelyUserContext, + holdout_decisions: Optional[list[Decision]] = None ) -> tuple[Decision, list[str]]: """ Determine which experiment/variation the user is in for a given rollout. Returns the variation of the first experiment the user qualifies for. @@ -562,7 +567,7 @@ def get_variation_for_rollout( flagKey: Feature key. rollout: Rollout for which we are getting the variation. user: ID and attributes for user. - options: Decide options. + holdout_decisions: If provided, local holdout decisions for skipped rules are appended to it. Returns: Decision namedtuple consisting of experiment and variation for the user and @@ -606,22 +611,14 @@ def get_variation_for_rollout( return Decision(experiment=rule, variation=forced_decision_variation, source=enums.DecisionSources.ROLLOUT, cmab_uuid=None), decide_reasons - local_holdouts = project_config.get_holdouts_for_rule(rule.id) - for holdout in local_holdouts: - local_holdout_decision = self.get_variation_for_holdout( - holdout, user_context, project_config - ) - decide_reasons.extend(local_holdout_decision['reasons']) - - local_decision = local_holdout_decision['decision'] - if local_decision.variation is not None: - message = ( - f"The user '{user_id}' is bucketed into local holdout '{holdout.key}' " - f"for delivery rule '{rule.key}'." - ) - self.logger.info(message) - decide_reasons.append(message) - return local_decision, decide_reasons + local_holdout = self._get_local_holdout_decision( + project_config, rule, user_context, 'delivery', decide_reasons + ) + if local_holdout is not None: + if holdout_decisions is not None: + holdout_decisions.append(local_holdout) + index += 1 + continue bucketing_id, bucket_reasons = self._get_bucketing_id(user_id, attributes) decide_reasons += bucket_reasons @@ -748,6 +745,7 @@ def get_decision_for_flag( global_holdout_result: DecisionResult | None = None global_holdout_key: str | None = None + holdout_decisions: list[Decision] = [] # Check global holdouts (flag level — before any rules are evaluated) global_holdouts = project_config.get_global_holdouts() @@ -781,6 +779,7 @@ def get_decision_for_flag( reasons.append(message) global_holdout_result = holdout_decision global_holdout_key = holdout.key + holdout_decisions.append(holdout_decision['decision']) break # Check experiments then rollouts @@ -807,30 +806,17 @@ def get_decision_for_flag( 'error': False, 'reasons': reasons } - if global_holdout_result is not None: - result['holdout_decision'] = global_holdout_result['decision'] + if holdout_decisions: + result['holdout_decisions'] = holdout_decisions + result['holdout_decision'] = holdout_decisions[0] return result - local_holdouts = project_config.get_holdouts_for_rule(experiment.id) - for holdout in local_holdouts: - local_holdout_decision = self.get_variation_for_holdout( - holdout, user_context, project_config - ) - reasons.extend(local_holdout_decision['reasons']) - - local_decision = local_holdout_decision['decision'] - if local_decision.variation is not None: - message = ( - f"The user '{user_id}' is bucketed into local holdout '{holdout.key}' " - f"for experiment rule '{experiment.key}'." - ) - self.logger.info(message) - reasons.append(message) - return { - 'decision': local_holdout_decision['decision'], - 'error': False, - 'reasons': reasons - } + local_holdout = self._get_local_holdout_decision( + project_config, experiment, user_context, 'experiment', reasons + ) + if local_holdout is not None: + holdout_decisions.append(local_holdout) + continue # Get variation for experiment variation_result = self.get_variation( @@ -856,8 +842,9 @@ def get_decision_for_flag( 'error': False, 'reasons': reasons } - if global_holdout_result is not None: - result['holdout_decision'] = global_holdout_result['decision'] + if holdout_decisions: + result['holdout_decisions'] = holdout_decisions + result['holdout_decision'] = holdout_decisions[0] return result if global_holdout_result is not None: @@ -870,7 +857,7 @@ def get_decision_for_flag( # If no experiment decision, check rollouts rollout_decision, rollout_reasons = self.get_variation_for_rollout( - project_config, feature_flag, user_context + project_config, feature_flag, user_context, holdout_decisions ) if rollout_reasons: reasons.extend(rollout_reasons) @@ -893,10 +880,33 @@ def get_decision_for_flag( 'error': False, 'reasons': reasons } - if global_holdout_result is not None: - final_result['holdout_decision'] = global_holdout_result['decision'] + if holdout_decisions: + final_result['holdout_decisions'] = holdout_decisions + final_result['holdout_decision'] = holdout_decisions[0] return final_result + def _get_local_holdout_decision( + self, + project_config: ProjectConfig, + rule: entities.Experiment, + user_context: OptimizelyUserContext, + rule_type: str, + reasons: list[str] + ) -> Optional[Decision]: + """Returns the first local holdout decision the user is bucketed into for the rule, if any.""" + for holdout in project_config.get_holdouts_for_rule(rule.id): + holdout_result = self.get_variation_for_holdout(holdout, user_context, project_config) + reasons.extend(holdout_result['reasons']) + if holdout_result['decision'].variation is not None: + message = ( + f"The user '{user_context.user_id}' is bucketed into local holdout '{holdout.key}' " + f"for {rule_type} rule '{rule.key}'. Skipping the rule." + ) + self.logger.info(message) + reasons.append(message) + return holdout_result['decision'] + return None + def get_variation_for_holdout( self, holdout: entities.Holdout, diff --git a/optimizely/optimizely.py b/optimizely/optimizely.py index 0f7c1da55..bcae0f1c4 100644 --- a/optimizely/optimizely.py +++ b/optimizely/optimizely.py @@ -1,4 +1,4 @@ -# Copyright 2016-2023, Optimizely +# Copyright 2016-2023, 2026, Optimizely # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -1246,7 +1246,7 @@ def _create_optimizely_decision( decision_reasons: Optional[list[str]], decide_options: list[str], project_config: ProjectConfig, - holdout_decision: Optional[Decision] = None + holdout_decisions: Optional[list[Decision]] = None ) -> OptimizelyDecision: user_id = user_context.user_id feature_enabled = False @@ -1265,24 +1265,25 @@ def _create_optimizely_decision( feature_flag = project_config.feature_key_map.get(flag_key) - # Send holdout impression when user was bucketed into a holdout bypassed due to exclude_targeted_deliveries - if (holdout_decision is not None + # Skipped local holdouts and global holdouts bypassed by exclude_targeted_deliveries + if (holdout_decisions and decision_source != DecisionSources.HOLDOUT and OptimizelyDecideOption.DISABLE_DECISION_EVENT not in decide_options): - holdout_enabled = self._get_feature_enabled(holdout_decision.variation) - holdout_rule_key = holdout_decision.experiment.key if holdout_decision.experiment else '' - self._send_impression_event( - project_config, - holdout_decision.experiment, - holdout_decision.variation, - flag_key, - holdout_rule_key, - str(DecisionSources.HOLDOUT), - holdout_enabled, - user_id, - attributes, - holdout_decision.cmab_uuid - ) + for holdout_decision in holdout_decisions: + holdout_enabled = self._get_feature_enabled(holdout_decision.variation) + holdout_rule_key = holdout_decision.experiment.key if holdout_decision.experiment else '' + self._send_impression_event( + project_config, + holdout_decision.experiment, + holdout_decision.variation, + flag_key, + holdout_rule_key, + str(DecisionSources.HOLDOUT), + holdout_enabled, + user_id, + attributes, + holdout_decision.cmab_uuid + ) decision_event_dispatched = True # Send impression event if Decision came from a feature @@ -1469,13 +1470,13 @@ def _decide_for_keys( user_context, merged_decide_options ) - holdout_decisions: dict[str, Optional[Decision]] = {} + holdout_decisions: dict[str, Optional[list[Decision]]] = {} for i in range(0, len(flags_without_forced_decision)): decision = decision_list[i]['decision'] reasons = decision_list[i]['reasons'] error = decision_list[i]['error'] flag_key = flags_without_forced_decision[i].key - holdout_decisions[flag_key] = decision_list[i].get('holdout_decision') + holdout_decisions[flag_key] = decision_list[i].get('holdout_decisions') # store error decision against key and remove key from valid keys if error: optimizely_decision = OptimizelyDecision.new_error_decision(flags_without_forced_decision[i].key, @@ -1496,7 +1497,7 @@ def _decide_for_keys( decision_reasons, merged_decide_options, project_config, - holdout_decision=holdout_decisions.get(key) + holdout_decisions=holdout_decisions.get(key) ) enabled_flags_only_missing = OptimizelyDecideOption.ENABLED_FLAGS_ONLY not in merged_decide_options is_enabled = optimizely_decision.enabled diff --git a/tests/test_decision_service.py b/tests/test_decision_service.py index b38a03b20..32d5ffdb0 100644 --- a/tests/test_decision_service.py +++ b/tests/test_decision_service.py @@ -1,4 +1,4 @@ -# Copyright 2017-2021, Optimizely +# Copyright 2017-2021, 2026, Optimizely # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -1510,7 +1510,7 @@ def test_get_variation_for_feature__returns_variation_for_feature_in_rollout(sel ) mock_get_variation_for_rollout.assert_called_once_with( - self.project_config, feature, user + self.project_config, feature, user, [] ) # Assert no log messages were generated diff --git a/tests/test_decision_service_holdout.py b/tests/test_decision_service_holdout.py index da85ae4e4..e0f57ecc0 100644 --- a/tests/test_decision_service_holdout.py +++ b/tests/test_decision_service_holdout.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import copy import json from unittest import mock @@ -19,6 +20,7 @@ from optimizely import error_handler from optimizely import logger from optimizely import optimizely as optimizely_module +from optimizely import user_profile from optimizely.decision.optimizely_decide_option import OptimizelyDecideOption from optimizely.helpers import enums from tests import base @@ -1467,8 +1469,8 @@ def test_global_holdout_miss_falls_through_to_experiment(self): # Branch 2: Local holdout hit — user bucketed into local holdout for rule X # ------------------------------------------------------------------ - def test_local_holdout_hit_returns_holdout_decision_for_experiment_rule(self): - """User bucketed into local holdout for experiment rule X returns holdout decision. + def test_local_holdout_hit_skips_experiment_rule(self): + """User bucketed into local holdout for experiment rule X is excluded from rule X only. The experiment rule ID is '111127' (test_experiment linked to test_feature_in_experiment). The local holdout targets only this rule with full traffic. @@ -1489,13 +1491,14 @@ def test_local_holdout_hit_returns_holdout_decision_for_experiment_rule(self): result = ds.get_decision_for_flag(feature_flag, user_ctx, config) decision = result['decision'] - # User must be caught by local holdout - self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) + self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) + self.assertIsNone(decision.variation) # Regular experiment evaluation (get_variation) must not have run mock_get_var.assert_not_called() + self.assertEqual([d.experiment.key for d in result['holdout_decisions']], ['local_for_exp']) - def test_local_holdout_hit_returns_holdout_decision_for_delivery_rule(self): - """User bucketed into local holdout for delivery/rollout rule returns holdout decision. + def test_local_holdout_hit_then_no_rule_serves(self): + """User held out of the everyone-else delivery rule and matching no other rule gets no variation. Rule '211147' is the everyone-else rollout rule for 'test_feature_in_rollout'. The local holdout targets this delivery rule with full traffic. @@ -1512,9 +1515,10 @@ def test_local_holdout_hit_returns_holdout_decision_for_delivery_rule(self): user_ctx = opt.create_user_context('user_delivery_holdout', {}) result = ds.get_decision_for_flag(feature_flag, user_ctx, config) - self.assertIsNotNone(result) decision = result['decision'] - self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) + self.assertEqual(decision.source, enums.DecisionSources.ROLLOUT) + self.assertIsNone(decision.variation) + self.assertEqual([d.experiment.key for d in result['holdout_decisions']], ['local_for_delivery']) # ------------------------------------------------------------------ # Branch 3: Local holdout miss — user falls through to regular rule evaluation @@ -1541,6 +1545,7 @@ def test_local_holdout_miss_falls_through_to_regular_rule_evaluation(self): decision = result['decision'] # Source must NOT be HOLDOUT — missed the local holdout self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) + self.assertNotIn('holdout_decisions', result) # ------------------------------------------------------------------ # Branch 4: Rule specificity — local holdout for rule X does NOT affect rule Y @@ -1607,7 +1612,8 @@ def test_local_holdout_applies_to_experiment_rule(self): user_ctx = opt.create_user_context('user_exp_holdout', {}) result = ds.get_decision_for_flag(feature_flag, user_ctx, config) - self.assertEqual(result['decision'].source, enums.DecisionSources.HOLDOUT) + self.assertNotEqual(result['decision'].source, enums.DecisionSources.HOLDOUT) + self.assertEqual(len(result['holdout_decisions']), 1) def test_local_holdout_applies_to_rollout_delivery_rule(self): """Local holdout check applies to rollout/delivery rules in get_decision_for_flag.""" @@ -1624,9 +1630,8 @@ def test_local_holdout_applies_to_rollout_delivery_rule(self): user_ctx = opt.create_user_context('user_delivery_holdout', {}) result = ds.get_decision_for_flag(feature_flag, user_ctx, config) - self.assertIsNotNone(result) - decision = result['decision'] - self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) + self.assertNotEqual(result['decision'].source, enums.DecisionSources.HOLDOUT) + self.assertEqual(len(result['holdout_decisions']), 1) # ------------------------------------------------------------------ # Precedence: Global → Forced → Local → Regular rule @@ -1709,6 +1714,236 @@ def test_no_holdouts_at_all_falls_through_to_experiment(self): decision = result['decision'] self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) + def _make_opt_exp_with_rollout(self, local_holdouts, send_flag_decisions=True): + """Experiment rule '111127' followed by delivery rules of rollout '211111' (everyone-else at 100%).""" + cfg = copy.deepcopy(self.config_dict_with_features) + cfg['sendFlagDecisions'] = send_flag_decisions + for flag in cfg['featureFlags']: + if flag['key'] == 'test_feature_in_experiment': + flag['rolloutId'] = '211111' + for rollout in cfg['rollouts']: + for rule in rollout['experiments']: + if rule['id'] == '211147': + rule['trafficAllocation'] = [{'entityId': '211149', 'endOfRange': 10000}] + cfg['holdouts'] = [] + cfg['localHoldouts'] = local_holdouts + self.opt_obj = optimizely_module.Optimizely(json.dumps(cfg)) + return self.opt_obj + + @staticmethod + def _holdout_impressions(mock_send): + return [c.args[1].key for c in mock_send.call_args_list + if c.args[5] == str(enums.DecisionSources.HOLDOUT)] + + def test_local_holdout_hit_then_later_rule_serves(self): + """Held out of experiment rule; the later delivery rule serves and both events are sent.""" + opt = self._make_opt_exp_with_rollout([_holdout('lh_exp', 'for_exp', included_rules=['111127'])]) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + + result = self._decision_svc().get_decision_for_flag( + feature_flag, opt.create_user_context('test_user', {}), config + ) + self.assertEqual(result['decision'].source, enums.DecisionSources.ROLLOUT) + self.assertEqual(result['decision'].experiment.id, '211147') + self.assertEqual([d.experiment.key for d in result['holdout_decisions']], ['for_exp']) + + with mock.patch.object(opt, '_send_impression_event', wraps=opt._send_impression_event) as mock_send: + decision = opt.create_user_context('test_user', {}).decide('test_feature_in_experiment') + + self.assertEqual(decision.rule_key, '211147') + self.assertEqual(self._holdout_impressions(mock_send), ['for_exp']) + self.assertEqual(mock_send.call_count, 2) + self.assertEqual(mock_send.call_args_list[1].args[5], str(enums.DecisionSources.ROLLOUT)) + + def test_local_holdout_hits_on_several_rules_send_several_holdout_events(self): + """Each rule's local holdout hit sends its own holdout impression.""" + opt = self._make_opt_exp_with_rollout([ + _holdout('lh_exp', 'for_exp', included_rules=['111127']), + _holdout('lh_del', 'for_del', included_rules=['211147']), + ]) + + with mock.patch.object(opt, '_send_impression_event', wraps=opt._send_impression_event) as mock_send: + decision = opt.create_user_context('test_user', {}).decide('test_feature_in_experiment') + + self.assertIsNone(decision.variation_key) + self.assertFalse(decision.enabled) + self.assertEqual(self._holdout_impressions(mock_send), ['for_exp', 'for_del']) + self.assertEqual(mock_send.call_count, 3) + final_call = mock_send.call_args_list[2] + self.assertEqual(final_call.args[5], str(enums.DecisionSources.ROLLOUT)) + self.assertIsNone(final_call.args[2]) + + def test_deprecated_holdout_decision_is_first_of_holdout_decisions(self): + opt = self._make_opt_exp_with_rollout([ + _holdout('lh_exp', 'for_exp', included_rules=['111127']), + _holdout('lh_del', 'for_del', included_rules=['211147']), + ]) + config = opt.config_manager.get_config() + + result = self._decision_svc().get_decision_for_flag( + config.get_feature_from_key('test_feature_in_experiment'), opt.create_user_context('test_user', {}), config + ) + self.assertEqual([d.experiment.key for d in result['holdout_decisions']], ['for_exp', 'for_del']) + self.assertIs(result['holdout_decision'], result['holdout_decisions'][0]) + + def test_one_local_holdout_on_two_rules_sends_two_holdout_events(self): + """A single local holdout targeting two rules is hit on each rule and sends an event per hit.""" + opt = self._make_opt_exp_with_rollout([ + _holdout('lh_shared', 'shared', included_rules=['111127', '211147']), + ]) + config = opt.config_manager.get_config() + + result = self._decision_svc().get_decision_for_flag( + config.get_feature_from_key('test_feature_in_experiment'), opt.create_user_context('test_user', {}), config + ) + self.assertEqual([d.experiment.key for d in result['holdout_decisions']], ['shared', 'shared']) + + with mock.patch.object(opt, '_send_impression_event', wraps=opt._send_impression_event) as mock_send: + decision = opt.create_user_context('test_user', {}).decide('test_feature_in_experiment') + + self.assertIsNone(decision.variation_key) + self.assertEqual(self._holdout_impressions(mock_send), ['shared', 'shared']) + self.assertEqual(mock_send.call_count, 3) + + def test_local_holdout_hit_beats_stored_variation_without_profile_save(self): + """A sticky stored variation for a held-out rule is not served and the profile is not updated.""" + opt = self._make_opt_exp_with_rollout([_holdout('lh_exp', 'for_exp', included_rules=['111127'])]) + config = opt.config_manager.get_config() + feature_flag = config.get_feature_from_key('test_feature_in_experiment') + ups = mock.MagicMock() + ups.lookup.return_value = { + 'user_id': 'test_user', 'experiment_bucket_map': {'111127': {'variation_id': '111129'}} + } + tracker = user_profile.UserProfileTracker('test_user', ups) + tracker.load_user_profile() + + result = self._decision_svc().get_decision_for_flag( + feature_flag, opt.create_user_context('test_user', {}), config, user_profile_tracker=tracker + ) + + self.assertEqual(result['decision'].experiment.id, '211147') + self.assertEqual([d.experiment.key for d in result['holdout_decisions']], ['for_exp']) + self.assertFalse(tracker.profile_updated) + + def test_local_holdout_hit_on_delivery_rule_sends_event_with_send_flag_decisions_off(self): + """Holdout impression is sent for a delivery-rule hit even when sendFlagDecisions is false.""" + opt = self._make_opt_exp_with_rollout( + [_holdout('lh_del', 'for_del', included_rules=['211147'])], send_flag_decisions=False + ) + + with mock.patch.object(opt, '_send_impression_event', wraps=opt._send_impression_event) as mock_send: + decision = opt.create_user_context('test_user', {}).decide('test_feature_in_rollout') + + self.assertIsNone(decision.variation_key) + self.assertEqual(self._holdout_impressions(mock_send), ['for_del']) + self.assertEqual(mock_send.call_count, 1) + + def test_legacy_api_skips_local_holdout_rule_without_holdout_event(self): + """is_feature_enabled skips a locally held-out rule without sending a holdout impression.""" + opt = self._make_opt_exp_with_rollout([_holdout('lh_exp', 'for_exp', included_rules=['111127'])]) + + with mock.patch.object(opt, '_send_impression_event', wraps=opt._send_impression_event) as mock_send: + opt.is_feature_enabled('test_feature_in_experiment', 'test_user') + + self.assertEqual(self._holdout_impressions(mock_send), []) + self.assertEqual([(c.args[4], c.args[5]) for c in mock_send.call_args_list], + [('211147', str(enums.DecisionSources.ROLLOUT))]) + + def test_disable_decision_event_suppresses_local_holdout_event(self): + """DISABLE_DECISION_EVENT suppresses the holdout impression for a skipped rule.""" + opt = self._make_opt_exp_with_rollout([_holdout('lh_exp', 'for_exp', included_rules=['111127'])]) + + with mock.patch.object(opt, '_send_impression_event', wraps=opt._send_impression_event) as mock_send: + decision = opt.create_user_context('test_user', {}).decide( + 'test_feature_in_experiment', [OptimizelyDecideOption.DISABLE_DECISION_EVENT] + ) + + self.assertEqual(decision.rule_key, '211147') + mock_send.assert_not_called() + + def test_local_holdout_hit_on_first_experiment_then_second_experiment_serves(self): + """Held out of the first experiment rule; the second experiment rule serves.""" + cfg = copy.deepcopy(self.config_dict_with_features) + cfg['experiments'].append({ + 'key': 'second_experiment', + 'status': 'Running', + 'forcedVariations': {}, + 'layerId': '111183', + 'audienceIds': [], + 'trafficAllocation': [{'entityId': '111141', 'endOfRange': 10000}], + 'id': '111140', + 'variations': [{'key': 'second_variation', 'id': '111141', 'featureEnabled': True, 'variables': []}], + }) + for flag in cfg['featureFlags']: + if flag['key'] == 'test_feature_in_experiment': + flag['experimentIds'] = ['111127', '111140'] + cfg['holdouts'] = [] + cfg['localHoldouts'] = [_holdout('lh_exp', 'for_exp', included_rules=['111127'])] + self.opt_obj = opt = optimizely_module.Optimizely(json.dumps(cfg)) + config = opt.config_manager.get_config() + + result = self._decision_svc().get_decision_for_flag( + config.get_feature_from_key('test_feature_in_experiment'), opt.create_user_context('test_user', {}), config + ) + self.assertEqual(result['decision'].source, enums.DecisionSources.FEATURE_TEST) + self.assertEqual(result['decision'].experiment.id, '111140') + self.assertEqual([d.experiment.key for d in result['holdout_decisions']], ['for_exp']) + + with mock.patch.object(opt, '_send_impression_event', wraps=opt._send_impression_event) as mock_send: + decision = opt.create_user_context('test_user', {}).decide('test_feature_in_experiment') + + self.assertEqual(decision.rule_key, 'second_experiment') + self.assertEqual(decision.variation_key, 'second_variation') + self.assertEqual(self._holdout_impressions(mock_send), ['for_exp']) + self.assertEqual(mock_send.call_count, 2) + self.assertEqual(mock_send.call_args_list[1].args[5], str(enums.DecisionSources.FEATURE_TEST)) + + def test_local_holdout_hit_then_later_rule_error_sends_no_impressions(self): + """Held out of the first rule; a CMAB error on the later rule yields an error decision and no events.""" + cfg = copy.deepcopy(self.config_dict_with_features) + cfg['experiments'].append({ + 'key': 'cmab_experiment', + 'status': 'Running', + 'forcedVariations': {}, + 'layerId': '111183', + 'audienceIds': [], + 'trafficAllocation': [{'entityId': '111141', 'endOfRange': 10000}], + 'id': '111140', + 'variations': [{'key': 'cmab_variation', 'id': '111141', 'featureEnabled': True, 'variables': []}], + 'cmab': {'attributeIds': [], 'trafficAllocation': 10000}, + }) + for flag in cfg['featureFlags']: + if flag['key'] == 'test_feature_in_experiment': + flag['experimentIds'] = ['111127', '111140'] + cfg['holdouts'] = [] + cfg['localHoldouts'] = [_holdout('lh_exp', 'for_exp', included_rules=['111127'])] + self.opt_obj = opt = optimizely_module.Optimizely(json.dumps(cfg)) + config = opt.config_manager.get_config() + holdout_hit = ("The user 'test_user' is bucketed into local holdout 'for_exp' " + "for experiment rule 'test_experiment'.") + cmab_error = enums.Errors.CMAB_FETCH_FAILED_DETAILED.format('cmab_experiment') + + with mock.patch.object(opt.decision_service.cmab_service, 'get_decision', side_effect=Exception('boom')): + result = opt.decision_service.get_decision_for_flag( + config.get_feature_from_key('test_feature_in_experiment'), + opt.create_user_context('test_user', {}), config + ) + self.assertTrue(result['error']) + self.assertEqual(result['decision'].experiment.id, '111140') + self.assertNotIn('holdout_decisions', result) + self.assertTrue(any(r.startswith(holdout_hit) for r in result['reasons'])) + self.assertIn(cmab_error, result['reasons']) + + with mock.patch.object(opt, '_send_impression_event', wraps=opt._send_impression_event) as mock_send: + decision = opt.create_user_context('test_user', {}).decide('test_feature_in_experiment') + + self.assertIsNone(decision.variation_key) + self.assertIsNone(decision.rule_key) + self.assertFalse(decision.enabled) + self.assertIn(cmab_error, decision.reasons) + mock_send.assert_not_called() + # --------------------------------------------------------------------------- # Exclude Targeted Deliveries Tests @@ -1858,7 +2093,7 @@ def test_global_holdout_exclude_td_true_blocks_ab_experiment(self): decision = result['decision'] self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) mock_get_var.assert_not_called() - self.assertIsNotNone(result.get('holdout_decision')) + self.assertIsNotNone(result.get('holdout_decisions')) # ------------------------------------------------------------------ # Test 4: Global holdout with exclude_targeted_deliveries=True, no TD matches @@ -1880,7 +2115,7 @@ def test_global_holdout_exclude_td_true_no_td_returns_non_holdout_decision(self) decision = result['decision'] self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) - self.assertIsNotNone(result.get('holdout_decision')) + self.assertIsNotNone(result.get('holdout_decisions')) expected_reason = ( "Holdout \"global_exclude_td\" has excludeTargetedDeliveries enabled, " @@ -1911,7 +2146,8 @@ def test_local_holdout_delivery_rule_exclude_td_true_still_applies(self): result = ds.get_decision_for_flag(feature_flag, user_ctx, config) decision = result['decision'] - self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) + self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) + self.assertEqual([d.experiment.key for d in result['holdout_decisions']], ['local_delivery_exclude']) # ------------------------------------------------------------------ # Test 6: Local holdout on experiment rule (TD type) with exclude_targeted_deliveries=True @@ -1937,7 +2173,8 @@ def test_local_holdout_td_experiment_exclude_td_true_still_applies(self): result = ds.get_decision_for_flag(feature_flag, user_ctx, config) decision = result['decision'] - self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) + self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) + self.assertEqual([d.experiment.key for d in result['holdout_decisions']], ['local_td_exclude']) # ------------------------------------------------------------------ # Test 7: Local holdout on experiment rule (A/B type) with exclude_targeted_deliveries=True @@ -1966,8 +2203,9 @@ def test_local_holdout_ab_experiment_exclude_td_true_still_applies(self): decision = result['decision'] # A/B experiment should still be blocked by local holdout - self.assertEqual(decision.source, enums.DecisionSources.HOLDOUT) + self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) mock_get_var.assert_not_called() + self.assertEqual([d.experiment.key for d in result['holdout_decisions']], ['local_ab_exclude']) # ------------------------------------------------------------------ # Test 8: Missing field (backward compatibility) @@ -1998,12 +2236,12 @@ def test_missing_exclude_td_field_defaults_to_false(self): self.assertFalse(holdout.exclude_targeted_deliveries) # ------------------------------------------------------------------ - # Test 9: TD match returns holdout_decision in result + # Test 9: TD match returns holdout_decisions in result # ------------------------------------------------------------------ def test_global_holdout_exclude_td_true_td_match_has_holdout_decision(self): """When exclude_targeted_deliveries=True and a TD experiment matches, - the result contains holdout_decision with the bypassed holdout.""" + the result contains holdout_decisions with the bypassed holdout.""" opt = self._make_opt_with_td( [_holdout_with_etd('gh1', 'global_exclude_td', exclude_targeted_deliveries=True)], experiment_type='td', @@ -2017,16 +2255,16 @@ def test_global_holdout_exclude_td_true_td_match_has_holdout_decision(self): decision = result['decision'] self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) - self.assertIsNotNone(result.get('holdout_decision')) - self.assertEqual(result['holdout_decision'].source, enums.DecisionSources.HOLDOUT) + self.assertEqual(len(result['holdout_decisions']), 1) + self.assertEqual(result['holdout_decisions'][0].source, enums.DecisionSources.HOLDOUT) # ------------------------------------------------------------------ - # Test 10: No TD match returns non-holdout with holdout_decision attached + # Test 10: No TD match returns non-holdout with holdout_decisions attached # ------------------------------------------------------------------ def test_global_holdout_exclude_td_true_no_td_has_holdout_decision(self): """When exclude_targeted_deliveries=True and no TD matches, - result is non-holdout but holdout_decision key is present, + result is non-holdout but holdout_decisions key is present, and reasons include the rollout evaluation continuation message.""" opt = self._make_opt_with_td( [_holdout_with_etd('gh1', 'global_exclude_td', exclude_targeted_deliveries=True)], @@ -2040,9 +2278,9 @@ def test_global_holdout_exclude_td_true_no_td_has_holdout_decision(self): decision = result['decision'] self.assertNotEqual(decision.source, enums.DecisionSources.HOLDOUT) - holdout_dec = result.get('holdout_decision') - self.assertIsNotNone(holdout_dec) - self.assertEqual(holdout_dec.source, enums.DecisionSources.HOLDOUT) + holdout_decs = result.get('holdout_decisions') + self.assertEqual(len(holdout_decs), 1) + self.assertEqual(holdout_decs[0].source, enums.DecisionSources.HOLDOUT) expected_reason = ( "Holdout \"global_exclude_td\" has excludeTargetedDeliveries enabled, " From 7649661eb29ea3c5616e2c38a6a47bef25ac39a7 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Mon, 2 Nov 2026 09:09:20 -0800 Subject: [PATCH 30/32] [AI-FSSDK] [FSSDK-13375] prepare for release python-sdk v5.8.0 (#527) * [FSSDK-13375] update CHANGELOG for python v5.8.0 Co-Authored-By: Claude Opus 5.5 (1M context) * [FSSDK-13375] bump version to 5.8.0 Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 16 ++++++++++++++++ optimizely/version.py | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f36a597e..78bed535b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Optimizely Python SDK Changelog +## 5.8.0 +October 30th, 2026 + +### Changed + +**Local Holdouts: rule evaluation continues after a holdout hit**: +When a user matches a local holdout on a rule, the SDK now excludes the user from that rule only +and continues evaluating the remaining rules, instead of returning the holdout variation and skipping +the rest of the flag. Each local holdout hit sends its own holdout impression event (using the +existing event format), regardless of `sendFlagDecisions`. Global holdouts are unchanged. + +- Continue rule evaluation after local holdout hit ([#525](https://github.com/optimizely/python-sdk/pull/525)) +- Remove dead Python 3.7 typing guards ([#526](https://github.com/optimizely/python-sdk/pull/526)) + +--- + ## 5.7.0 September 2nd, 2026 diff --git a/optimizely/version.py b/optimizely/version.py index 88def8194..ea3017629 100644 --- a/optimizely/version.py +++ b/optimizely/version.py @@ -11,5 +11,5 @@ # See the License for the specific language governing permissions and # limitations under the License. -version_info = (5, 7, 0) +version_info = (5, 8, 0) __version__ = '.'.join(str(v) for v in version_info) From c792eac75da162efd33e843e5247a3af69ec07d8 Mon Sep 17 00:00:00 2001 From: Esra Kartal <102107327+esrakartalOpt@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:12:41 -0600 Subject: [PATCH 31/32] [FSSDK-13482] Fix Arnica findings: setup.py exec and http session mount (#529) * [FSSDK-13482] Fix Arnica findings: setup.py exec and http session mount - setup.py: read the version by parsing the version_info literal from optimizely/version.py instead of exec()-ing the file. - Add create_retry_session helper and use it in event_dispatcher and config_manager, replacing three duplicated session.mount('http://', ...) blocks with one documented, suppressed call. Behavior is unchanged. Co-Authored-By: Claude Sonnet 5.5 * [FSSDK-13482] Fix mypy: allow Optional retries in create_retry_session config_manager passes self.retries, which is Optional[int]. Accept Optional[int] (None means no total limit, same as urllib3's Retry) so type-check passes. Co-Authored-By: Claude Sonnet 5.5 * [FSSDK-13482] Drop Python 3.9 from the CI test matrix Python 3.9 reached end of life in October 2025 and setup-python no longer finds a 3.9 build on ubuntu-latest (now Ubuntu 26.04), so the test (3.9) job failed before running any tests. Co-Authored-By: Claude Sonnet 5.5 * Revert python version drop from CI test matrix * [FSSDK-13482] Address review: default status_forcelist, trim duplicated http:// note - Default status_forcelist to (500, 502, 503, 504) in create_retry_session and drop the argument from the three callers. - Keep the http:// explanation next to the mount call and shorten the docstring. - Add a test for the default status_forcelist. Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 --- optimizely/config_manager.py | 25 +++--------- optimizely/event_dispatcher.py | 15 ++----- optimizely/helpers/retry_session.py | 50 +++++++++++++++++++++++ setup.py | 9 +++- tests/helpers_tests/test_retry_session.py | 38 +++++++++++++++++ 5 files changed, 103 insertions(+), 34 deletions(-) create mode 100644 optimizely/helpers/retry_session.py create mode 100644 tests/helpers_tests/test_retry_session.py diff --git a/optimizely/config_manager.py b/optimizely/config_manager.py index 22468b05b..ccad8d087 100644 --- a/optimizely/config_manager.py +++ b/optimizely/config_manager.py @@ -19,8 +19,6 @@ import threading from requests import codes as http_status_codes from requests import exceptions as requests_exceptions -from requests.adapters import HTTPAdapter -from urllib3.util.retry import Retry from . import exceptions as optimizely_exceptions from . import logger as optimizely_logger @@ -30,6 +28,7 @@ from .notification_center_registry import _NotificationCenterRegistry from .helpers import enums from .helpers import validator +from .helpers.retry_session import create_retry_session from .optimizely_config import OptimizelyConfig, OptimizelyConfigService @@ -392,15 +391,8 @@ def fetch_datafile(self) -> None: request_headers[enums.HTTPHeaders.IF_MODIFIED_SINCE] = self.last_modified try: - session = requests.Session() - - retries = Retry(total=self.retries, - backoff_factor=0.1, - status_forcelist=[500, 502, 503, 504]) - adapter = HTTPAdapter(max_retries=retries) - - session.mount('http://', adapter) - session.mount("https://", adapter) + session = create_retry_session(retries=self.retries, + backoff_factor=0.1) response = session.get(self.datafile_url, headers=request_headers, timeout=enums.ConfigManager.REQUEST_TIMEOUT) @@ -485,15 +477,8 @@ def fetch_datafile(self) -> None: request_headers[enums.HTTPHeaders.IF_MODIFIED_SINCE] = self.last_modified try: - session = requests.Session() - - retries = Retry(total=self.retries, - backoff_factor=0.1, - status_forcelist=[500, 502, 503, 504]) - adapter = HTTPAdapter(max_retries=retries) - - session.mount('http://', adapter) - session.mount("https://", adapter) + session = create_retry_session(retries=self.retries, + backoff_factor=0.1) response = session.get(self.datafile_url, headers=request_headers, timeout=enums.ConfigManager.REQUEST_TIMEOUT) diff --git a/optimizely/event_dispatcher.py b/optimizely/event_dispatcher.py index cf4683401..f97605981 100644 --- a/optimizely/event_dispatcher.py +++ b/optimizely/event_dispatcher.py @@ -15,13 +15,11 @@ import logging from typing import Protocol -import requests from requests import exceptions as request_exception -from requests.adapters import HTTPAdapter -from urllib3.util.retry import Retry from . import event_builder from .helpers.enums import HTTPVerbs, EventDispatchConfig +from .helpers.retry_session import create_retry_session class CustomEventDispatcher(Protocol): @@ -41,15 +39,8 @@ def dispatch_event(event: event_builder.Event) -> None: event: Object holding information about the request to be dispatched to the Optimizely backend. """ try: - session = requests.Session() - - retries = Retry(total=EventDispatchConfig.RETRIES, - backoff_factor=0.2, - status_forcelist=[500, 502, 503, 504]) - adapter = HTTPAdapter(max_retries=retries) - - session.mount('http://', adapter) - session.mount("https://", adapter) + session = create_retry_session(retries=EventDispatchConfig.RETRIES, + backoff_factor=0.2) if event.http_verb == HTTPVerbs.GET: session.get(event.url, params=event.params, diff --git a/optimizely/helpers/retry_session.py b/optimizely/helpers/retry_session.py new file mode 100644 index 000000000..b01f7232d --- /dev/null +++ b/optimizely/helpers/retry_session.py @@ -0,0 +1,50 @@ +# Copyright 2026, Optimizely +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from typing import Optional, Sequence + +import requests +from requests.adapters import HTTPAdapter +from urllib3.util.retry import Retry + + +def create_retry_session( + retries: Optional[int], backoff_factor: float, status_forcelist: Sequence[int] = (500, 502, 503, 504) +) -> requests.Session: + """ Create a requests session that retries failed requests. + + The same retry adapter is registered for both https:// and http:// URLs. + + Args: + retries: Total number of retries. None means no total limit (same as urllib3's Retry). + backoff_factor: Backoff factor between retries. + status_forcelist: HTTP status codes that should trigger a retry. Defaults to 500, 502, 503 and 504. + + Returns: + A configured requests.Session. + """ + session = requests.Session() + + retry = Retry(total=retries, + backoff_factor=backoff_factor, + status_forcelist=status_forcelist) + adapter = HTTPAdapter(max_retries=retry) + + # http:// kept so retries still apply to user-configured http:// datafile URLs / event endpoints. + # nosemgrep + session.mount('http://', adapter) + session.mount('https://', adapter) + + return session diff --git a/setup.py b/setup.py index 1954aa489..18c9d1d7b 100644 --- a/setup.py +++ b/setup.py @@ -1,4 +1,6 @@ +import ast import os +import re from setuptools import setup from setuptools import find_packages @@ -6,9 +8,12 @@ here = os.path.join(os.path.dirname(__file__)) -__version__ = None +# Read the version without executing version.py: parse the version_info tuple literal instead. with open(os.path.join(here, 'optimizely', 'version.py')) as _file: - exec(_file.read()) + _version_match = re.search(r'^version_info\s*=\s*(\(.*\))\s*$', _file.read(), re.MULTILINE) +if _version_match is None: + raise RuntimeError('Unable to find version_info in optimizely/version.py') +__version__ = '.'.join(str(v) for v in ast.literal_eval(_version_match.group(1))) with open(os.path.join(here, 'requirements', 'core.txt')) as _file: REQUIREMENTS = _file.read().splitlines() diff --git a/tests/helpers_tests/test_retry_session.py b/tests/helpers_tests/test_retry_session.py new file mode 100644 index 000000000..8f52ec763 --- /dev/null +++ b/tests/helpers_tests/test_retry_session.py @@ -0,0 +1,38 @@ +# Copyright 2026, Optimizely +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +import requests +from requests.adapters import HTTPAdapter + +from optimizely.helpers.retry_session import create_retry_session + + +class CreateRetrySessionTest(unittest.TestCase): + def test_returns_session_with_retry_adapter_for_https_and_http(self): + session = create_retry_session(retries=3, backoff_factor=0.2, status_forcelist=[500, 503]) + + self.assertIsInstance(session, requests.Session) + for prefix in ('https://', 'http://'): + adapter = session.get_adapter(prefix + 'example.com') + self.assertIsInstance(adapter, HTTPAdapter) + self.assertEqual(3, adapter.max_retries.total) + self.assertEqual(0.2, adapter.max_retries.backoff_factor) + self.assertEqual([500, 503], list(adapter.max_retries.status_forcelist)) + + def test_status_forcelist_defaults_to_server_error_codes(self): + session = create_retry_session(retries=3, backoff_factor=0.2) + + adapter = session.get_adapter('https://example.com') + self.assertEqual([500, 502, 503, 504], list(adapter.max_retries.status_forcelist)) From fbfed74487bfc6ead575bd68830936d61920514b Mon Sep 17 00:00:00 2001 From: Farhan Anjum Date: Thu, 26 Nov 2026 18:49:13 +0600 Subject: [PATCH 32/32] =?UTF-8?q?[FSSDK-13301]=20Raise=20minimum=20Python?= =?UTF-8?q?=20to=203.10,=20add=203.13=E2=80=933.15=20(#530)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [FSSDK-13301] Raise minimum Python to 3.10, add 3.13–3.15 - Remove the last version_info < (3, 10) guard; import TypeGuard from typing - setup.py: add python_requires='>=3.10'; classifiers 3.10–3.15 - README: add 5.9+ requirements row and EOL support policy - ruff target-version py39 -> py310 - CI: test on 3.10–3.15 and pypy-3.10/3.11/3.12; type-check on 3.10–3.15 Co-Authored-By: Claude Opus 5.5 * [FSSDK-13301] README: explain why Python version drops are minor releases Co-Authored-By: Claude Opus 5.5 * [FSSDK-13301] Make polling-thread failure test independent of CPython wording The test forced a crash with a huge update_interval and matched CPython's OverflowError text, which changed in recent 3.13/3.14/3.15 patch releases. It could also pass without asserting anything if stop() won the race. Mock fetch_datafile to raise a known exception instead, and assert that the exception leaves the thread and is logged once. Also drop the README "Version 5.9+" row: the next version number is decided at release time, so the release PR adds that row. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .github/workflows/python.yml | 17 +++++++----- README.md | 2 ++ optimizely/event/event_id_normalizer.py | 8 +----- ruff.toml | 2 +- setup.py | 6 +++-- tests/test_config_manager.py | 36 ++++++++++--------------- 6 files changed, 32 insertions(+), 39 deletions(-) diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 830ca0f44..5283b5864 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -64,12 +64,15 @@ jobs: fail-fast: false matrix: python-version: - - "pypy-3.9" - "pypy-3.10" - - "3.9" + - "pypy-3.11" + - "pypy-3.12" - "3.10" - "3.11" - "3.12" + - "3.13" + - "3.14" + - "3.15" steps: - uses: actions/checkout@v3 with: @@ -92,13 +95,13 @@ jobs: fail-fast: false matrix: python-version: - # disabled due to librt is not available on this pypy version - # - "pypy-3.9" - # - "pypy-3.10" - # - "3.9" - # - "3.10" + # CPython only: mypy depends on librt, which publishes no PyPy wheels + - "3.10" - "3.11" - "3.12" + - "3.13" + - "3.14" + - "3.15" steps: - uses: actions/checkout@v3 with: diff --git a/README.md b/README.md index e0aeafb62..13df31e33 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,8 @@ Version `4.0+`: Python 3.7+, PyPy 3.7+ Version `3.0+`: Python 2.7+, PyPy 3.4+ +Dropping support for an end-of-life Python version doesn't change the SDK's public API, so it ships in a minor release rather than a major one. Each release declares its minimum Python (`python_requires`), so pip on an older Python installs the last compatible release instead. For example, Python 3.8 and 3.9 stay on 5.8.x. + ### Install the SDK The SDK is available through [PyPi](https://pypi.python.org/pypi?name=optimizely-sdk&:action=display). diff --git a/optimizely/event/event_id_normalizer.py b/optimizely/event/event_id_normalizer.py index f2d4235d1..5bf7103e6 100644 --- a/optimizely/event/event_id_normalizer.py +++ b/optimizely/event/event_id_normalizer.py @@ -37,13 +37,7 @@ """ -from sys import version_info -from typing import Any, Optional - -if version_info < (3, 10): - from typing_extensions import TypeGuard -else: - from typing import TypeGuard +from typing import Any, Optional, TypeGuard def is_non_empty_string(value: Any) -> TypeGuard[str]: diff --git a/ruff.toml b/ruff.toml index 5365a7b4d..289c7c599 100644 --- a/ruff.toml +++ b/ruff.toml @@ -2,7 +2,7 @@ # https://docs.astral.sh/ruff/configuration/ line-length = 120 -target-version = "py39" +target-version = "py310" exclude = [ ".git", diff --git a/setup.py b/setup.py index 18c9d1d7b..8aac986a5 100644 --- a/setup.py +++ b/setup.py @@ -52,14 +52,16 @@ 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3.12', + 'Programming Language :: Python :: 3.13', + 'Programming Language :: Python :: 3.14', + 'Programming Language :: Python :: 3.15', ], packages=find_packages(exclude=['docs', 'tests']), extras_require={'test': TEST_REQUIREMENTS}, + python_requires='>=3.10', install_requires=REQUIREMENTS, tests_require=TEST_REQUIREMENTS, test_suite='tests', diff --git a/tests/test_config_manager.py b/tests/test_config_manager.py index 8fa196933..96bb5ecb9 100644 --- a/tests/test_config_manager.py +++ b/tests/test_config_manager.py @@ -556,32 +556,24 @@ def test_fetch_datafile__request_exception_raised(self, _): def test_fetch_datafile__exception_polling_thread_failed(self, _): """ Test that exception is raised when polling thread stops. """ - sdk_key = 'some_key' mock_logger = mock.Mock() + thread_exceptions = [] - test_headers = {'Last-Modified': 'New Time'} - test_datafile = json.dumps(self.config_dict_with_features) - test_response = requests.Response() - test_response.status_code = 200 - test_response.headers = test_headers - test_response._content = test_datafile - - with mock.patch('requests.Session.get', return_value=test_response): - project_config_manager = config_manager.PollingConfigManager(sdk_key=sdk_key, - logger=mock_logger, - update_interval=12345678912345) + with ( + mock.patch('optimizely.config_manager.PollingConfigManager.fetch_datafile', + side_effect=Exception('boom')), + mock.patch('threading.excepthook', side_effect=thread_exceptions.append), + ): + project_config_manager = config_manager.PollingConfigManager(sdk_key='some_key', logger=mock_logger) + project_config_manager._polling_thread.join(timeout=2) - project_config_manager.stop() + # the exception is raised out of the polling thread, which stops + self.assertFalse(project_config_manager.is_running) + self.assertEqual(1, len(thread_exceptions)) + self.assertEqual('boom', str(thread_exceptions[0].exc_value)) - # verify the error log message - log_messages = [args[0] for args, _ in mock_logger.error.call_args_list] - for message in log_messages: - print(message) - # Check for key parts of the error message (version-agnostic for Python 3.11+) - if not ("Thread for background datafile polling failed" in message and - "timestamp too large to convert to C" in message and - "PyTime_t" in message): - assert False + # and it is logged before being raised + mock_logger.error.assert_called_once_with('Thread for background datafile polling failed. Error: boom') def test_is_running(self, _): """ Test that polling thread is running after instance of PollingConfigManager is created. """