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/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 0699f84c0..5283b5864 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,21 +31,18 @@ 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: 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 @@ -65,16 +64,19 @@ jobs: fail-fast: false matrix: python-version: - - "pypy-3.8" - - "pypy-3.9" - "pypy-3.10" - - "3.8" - - "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: + persist-credentials: false - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: @@ -93,16 +95,17 @@ jobs: fail-fast: false matrix: python-version: - - "pypy-3.8" - - "pypy-3.9" - - "pypy-3.10" - - "3.8" - - "3.9" + # 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: + 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 diff --git a/CHANGELOG.md b/CHANGELOG.md index d0cd8b719..78bed535b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,159 @@ # 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 + +### 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 + +### 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 + +### 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 + +### 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 + +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/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/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/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 1bd7ff527..e21fb865e 100644 --- a/optimizely/bucketer.py +++ b/optimizely/bucketer.py @@ -12,23 +12,16 @@ # limitations under the License. from __future__ import annotations -from typing import Optional, TYPE_CHECKING +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 # type: ignore - - 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 +97,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: @@ -119,21 +112,36 @@ def bucket( and array of log messages representing decision making. */. """ - 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) - return variation, decide_reasons + # 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, [] + + # Handle both Experiment and Holdout entities + experiment_key = experiment.key + experiment_id = experiment.id - else: - message = 'Bucketed into an empty traffic range. Returning nil.' - project_config.logger.info(message) - decide_reasons.append(message) + 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) + # 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.' + project_config.logger.info(message) + decide_reasons.append(message) return None, decide_reasons 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. @@ -151,44 +159,55 @@ def bucket_to_entity_id( if not experiment: return None, decide_reasons - # Determine if experiment is in a mutually exclusive group. - # This will not affect evaluation of rollout rules. - if experiment.groupPolicy in GROUP_POLICIES: - group = project_config.get_group(experiment.groupId) - - if not group: - return None, decide_reasons - - 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 user_experiment_id != experiment.id: - message = f'User "{user_id}" is not in experiment "{experiment.key}" of group {experiment.groupId}.' + # 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) + + if not group: + return None, decide_reasons + + 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 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}.' 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) - - traffic_allocations: list[TrafficAllocation] = experiment.trafficAllocation - if experiment.cmab: + # 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, - experiment.id, traffic_allocations) + experiment_id, traffic_allocations) return variation_id, decide_reasons diff --git a/optimizely/cmab/cmab_client.py b/optimizely/cmab/cmab_client.py index dfcffa781..4880b0bbb 100644 --- a/optimizely/cmab/cmab_client.py +++ b/optimizely/cmab/cmab_client.py @@ -20,11 +20,12 @@ 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 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/cmab/cmab_service.py b/optimizely/cmab/cmab_service.py index a7c4b69bc..081ecf512 100644 --- a/optimizely/cmab/cmab_service.py +++ b/optimizely/cmab/cmab_service.py @@ -13,14 +13,20 @@ import uuid import json 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 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 +DEFAULT_CMAB_CACHE_TIMEOUT = 30 * 60 # 30 minutes +DEFAULT_CMAB_CACHE_SIZE = 10000 class CmabDecision(TypedDict): @@ -52,21 +58,50 @@ 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: + 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]) -> 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) @@ -75,17 +110,39 @@ def get_decision(self, project_config: ProjectConfig, user_context: OptimizelyUs 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()) @@ -106,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/optimizely/config_manager.py b/optimizely/config_manager.py index 3dce27412..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 @@ -145,14 +144,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 @@ -236,9 +235,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 ) @@ -395,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) @@ -488,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/decision/optimizely_decide_option.py b/optimizely/decision/optimizely_decide_option.py index 8cffcfec1..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 # 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..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 # type: ignore +from typing import Final class OptimizelyDecisionMessage: diff --git a/optimizely/decision_service.py b/optimizely/decision_service.py index d22bec87c..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 @@ -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 VariationDict from . import bucketer from . import entities @@ -59,18 +61,15 @@ 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): - """ - A TypedDict representing the result of a decision process. +class _DecisionResultOptional(TypedDict, total=False): + holdout_decision: Decision # Deprecated: first entry of holdout_decisions. + holdout_decisions: List[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] @@ -79,8 +78,8 @@ 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] - variation: Optional[entities.Variation] + experiment: Optional[Union[entities.Experiment, entities.Holdout]] + variation: Optional[Union[entities.Variation, VariationDict]] source: Optional[str] cmab_uuid: Optional[str] @@ -175,9 +174,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, @@ -243,7 +243,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} @@ -258,7 +262,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: @@ -299,7 +303,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) @@ -307,7 +313,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. @@ -338,7 +344,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: @@ -355,8 +361,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 @@ -423,7 +431,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: @@ -504,6 +512,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, @@ -540,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. @@ -550,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 @@ -594,6 +611,15 @@ def get_variation_for_rollout( return Decision(experiment=rule, variation=forced_decision_variation, source=enums.DecisionSources.ROLLOUT, cmab_uuid=None), 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 @@ -669,7 +695,315 @@ 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] + # 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 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, + 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 + + 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() + for holdout in global_holdouts: + holdout_decision = self.get_variation_for_holdout(holdout, user_context, project_config) + reasons.extend(holdout_decision['reasons']) + + decision = holdout_decision['decision'] + 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) + + 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 + holdout_decisions.append(holdout_decision['decision']) + 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) + 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) + result: DecisionResult = { + 'decision': decision, + 'error': False, + 'reasons': reasons + } + if holdout_decisions: + result['holdout_decisions'] = holdout_decisions + result['holdout_decision'] = holdout_decisions[0] + return result + + 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( + 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']) + result = { + 'decision': decision, + 'error': False, + 'reasons': reasons + } + if holdout_decisions: + result['holdout_decisions'] = holdout_decisions + result['holdout_decision'] = holdout_decisions[0] + 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( + project_config, feature_flag, user_context, holdout_decisions + ) + 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 + + 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}".') + + final_result: DecisionResult = { + 'decision': rollout_decision, + 'error': False, + 'reasons': reasons + } + 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, + user_context: OptimizelyUserContext, + project_config: ProjectConfig + ) -> DecisionResult: + """ + Get the variation for holdout. + + Args: + holdout: The holdout configuration (Holdout entity). + 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() + + # 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 { + '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 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.key, + 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 + ) + decide_reasons.extend(bucket_reasons) + + if variation: + 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}'." + ) + self.logger.info(message) + decide_reasons.append(message) + + holdout_decision: Decision = Decision( + experiment=holdout, + 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, @@ -756,100 +1090,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 = 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 7d2576565..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 # type: ignore +from typing import TYPE_CHECKING, Any, Optional, Sequence, Final if TYPE_CHECKING: @@ -27,6 +21,8 @@ class BaseEntity: def __eq__(self, other: object) -> bool: + if not hasattr(other, '__dict__'): + return False return self.__dict__ == other.__dict__ @@ -85,6 +81,7 @@ def __init__( groupId: Optional[str] = None, groupPolicy: Optional[str] = None, cmab: Optional[CmabDict] = None, + type: Optional[str] = None, **kwargs: Any ): self.id = id @@ -99,6 +96,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. """ @@ -194,3 +192,88 @@ 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], + audienceConditions: Optional[Sequence[str | list[str]]] = None, + includedRules: Optional[list[str]] = None, + excludeTargetedDeliveries: bool = False, + **kwargs: Any + ): + self.id = id + self.key = key + self.status = status + self.variations = variations + self.trafficAllocation = trafficAllocation + self.audienceIds = audienceIds + self.audienceConditions = audienceConditions + # 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. + + 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_global(self) -> bool: + """True if this is a global holdout. + + 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 + + @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 c872fb178..34bc04e2f 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 @@ -12,21 +12,16 @@ # 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 from optimizely.helpers import validator +from . import event_id_normalizer from . import log_event from . import payload from . import user_event -if version_info < (3, 8): - from typing_extensions import Final -else: - from typing import Final # type: ignore - if TYPE_CHECKING: # prevent circular dependenacy by skipping import at runtime from optimizely.project_config import ProjectConfig @@ -125,17 +120,28 @@ 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 + + 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..5bf7103e6 --- /dev/null +++ b/optimizely/event/event_id_normalizer.py @@ -0,0 +1,87 @@ +# 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 typing import Any, Optional, 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/event_processor.py b/optimizely/event/event_processor.py index 05f5e078b..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 # type: ignore - - class BaseEventProcessor(ABC): """ Class encapsulating event processing. Override with your own implementation. """ @@ -72,7 +65,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/event/log_event.py b/optimizely/event/log_event.py index 7c0beeb62..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 # type: ignore - - class LogEvent(event_builder.Event): """ Representation of an event which can be sent to Optimizely events API. """ 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/user_event.py b/optimizely/event/user_event.py index e257647cb..a2cb2df70 100644 --- a/optimizely/event/user_event.py +++ b/optimizely/event/user_event.py @@ -13,23 +13,17 @@ 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 # type: ignore - - 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 +57,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/event_builder.py b/optimizely/event_builder.py index 90678830d..67169d2a8 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 @@ -13,20 +13,15 @@ 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 from .helpers import enums 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 # type: ignore - if TYPE_CHECKING: # prevent circular dependenacy by skipping import at runtime from .entities import Experiment @@ -178,7 +173,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 +183,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/event_dispatcher.py b/optimizely/event_dispatcher.py index 767fbb7dd..f97605981 100644 --- a/optimizely/event_dispatcher.py +++ b/optimizely/event_dispatcher.py @@ -13,20 +13,13 @@ import json import logging -from sys import version_info +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 - -if version_info < (3, 8): - from typing_extensions import Protocol -else: - from typing import Protocol # type: ignore +from .helpers.retry_session import create_retry_session class CustomEventDispatcher(Protocol): @@ -46,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.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=EventDispatchConfig.RETRIES, + backoff_factor=0.2) if event.http_verb == HTTPVerbs.GET: session.get(event.url, params=event.params, diff --git a/optimizely/helpers/condition.py b/optimizely/helpers/condition.py index 58000a909..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 # type: ignore - - class ConditionOperatorTypes: AND: Final = 'and' OR: Final = 'or' diff --git a/optimizely/helpers/enums.py b/optimizely/helpers/enums.py index e3acafef2..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 # type: ignore +from typing import Final class CommonAudienceEvaluationLogs: @@ -99,6 +94,7 @@ class DecisionSources: EXPERIMENT: Final = 'experiment' FEATURE_TEST: Final = 'feature-test' ROLLOUT: Final = 'rollout' + HOLDOUT: Final = 'holdout' class Errors: @@ -228,6 +224,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/event_tag_utils.py b/optimizely/helpers/event_tag_utils.py index cb577950b..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 # type: ignore if TYPE_CHECKING: 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/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/helpers/types.py b/optimizely/helpers/types.py index 3cca45de1..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 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. @@ -115,3 +108,21 @@ class CmabDict(BaseEntity): """Cmab dict from parsed datafile json.""" attributeIds: list[str] trafficAllocation: int + + +ExperimentType = Literal[ + 'ab', 'mab', 'cmab', 'td', 'fr' +] + +HoldoutStatus = Literal['Draft', 'Running', 'Concluded', 'Archived'] + + +class HoldoutDict(ExperimentDict): + """Holdout dict from parsed datafile json. + + Extends ExperimentDict with holdout-specific properties. + """ + holdoutStatus: HoldoutStatus + # 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/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/optimizely/logger.py b/optimizely/logger.py index 33d3660c9..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 # type: ignore - _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..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 # type: ignore NOTIFICATION_TYPES: Final = tuple( diff --git a/optimizely/odp/lru_cache.py b/optimizely/odp/lru_cache.py index 073973e64..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 # type: ignore +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/odp_event_manager.py b/optimizely/odp/odp_event_manager.py index 85512e909..a7bd09067 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}')) @@ -260,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/odp/optimizely_odp_option.py b/optimizely/odp/optimizely_odp_option.py index ce6eaf006..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 # type: ignore +from typing import Final class OptimizelyOdpOption: diff --git a/optimizely/optimizely.py b/optimizely/optimizely.py index ae433cb17..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 @@ -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 @@ -46,17 +48,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 +75,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,19 +177,90 @@ 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: + # 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, + prediction_endpoint=cmab_prediction_endpoint + ) + 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 + 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. @@ -259,8 +329,9 @@ def _validate_user_inputs( return True 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, + 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: """ Helper method to send impression event. @@ -279,7 +350,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, @@ -365,7 +436,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( @@ -383,10 +454,10 @@ 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': decision.variation.key if decision.variation else None, + 'variation_key': self._get_variation_key(decision.variation), } try: @@ -454,7 +525,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}".' @@ -490,7 +561,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( @@ -555,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, @@ -663,7 +735,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 @@ -728,7 +800,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(): @@ -741,7 +813,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, @@ -1050,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. @@ -1170,12 +1245,13 @@ def _create_optimizely_decision( flag_decision: Decision, decision_reasons: Optional[list[str]], decide_options: list[str], - project_config: ProjectConfig + project_config: ProjectConfig, + holdout_decisions: Optional[list[Decision]] = None ) -> OptimizelyDecision: 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}"') @@ -1189,10 +1265,32 @@ def _create_optimizely_decision( feature_flag = project_config.feature_key_map.get(flag_key) + # 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): + 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 - # 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, @@ -1224,11 +1322,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 @@ -1241,7 +1335,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'") @@ -1376,11 +1470,13 @@ def _decide_for_keys( user_context, merged_decide_options ) + 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_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, @@ -1400,7 +1496,8 @@ def _decide_for_keys( flag_decision, decision_reasons, merged_decide_options, - project_config + project_config, + holdout_decisions=holdout_decisions.get(key) ) enabled_flags_only_missing = OptimizelyDecideOption.ENABLED_FLAGS_ONLY not in merged_decide_options is_enabled = optimizely_decision.enabled @@ -1469,7 +1566,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 @@ -1479,7 +1576,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_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/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/optimizely/project_config.py b/optimizely/project_config.py index 446d1e2fa..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, 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,14 +20,10 @@ from .helpers import enums from .helpers import types -if version_info < (3, 8): - from typing_extensions import Final -else: - from typing import Final # type: ignore - if TYPE_CHECKING: # prevent circular dependenacy by skipping import at runtime from .logger import Logger + from .helpers.types import VariationDict SUPPORTED_VERSIONS = [ @@ -88,6 +83,66 @@ def __init__(self, datafile: str | bytes, logger: Logger, error_handler: Any): region_value = config.get('region') self.region: str = region_value or 'US' + # Parse holdouts from datafile and convert to Holdout entities + 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 — 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]] = {} + + # 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 — 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) + + # Only process Running holdouts + if not holdout.is_activated: + continue + + # Map by ID for quick lookup + self.holdout_id_map[holdout.id] = 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( @@ -139,11 +194,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(): @@ -157,11 +212,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) @@ -186,6 +243,38 @@ 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]) + + # 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 + ) + rollout = None if len(feature.rolloutId) == 0 else self.rollout_id_map[feature.rolloutId] if rollout: for exp in rollout.experiments: @@ -195,10 +284,29 @@ 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: + # 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( entity_list: Iterable[Any], key: str, entity_class: Type[EntityClass], first_value: bool = False @@ -415,7 +523,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: @@ -442,7 +552,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: @@ -582,8 +694,43 @@ 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[entities.Variation] + self, variable: Optional[entities.Variable], variation: Optional[Union[entities.Variation, VariationDict]] ) -> Optional[str]: """ Get the variable value for the given variation. @@ -597,12 +744,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 @@ -611,7 +767,6 @@ def get_variable_value_for_variation( if variable_usage: variable_value = variable_usage.value - else: variable_value = variable.defaultValue @@ -680,7 +835,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: @@ -699,7 +854,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: @@ -752,3 +907,49 @@ def get_flag_variation( return variation return None + + def get_global_holdouts(self) -> list[entities.Holdout]: + """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. + """ + return self.global_holdouts + + def get_holdouts_for_rule(self, rule_id: str) -> list[entities.Holdout]: + """Return local holdouts that target a specific rule. + + 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. + + 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. + + Args: + holdout_id: ID of the holdout. + + Returns: + The holdout corresponding to the provided holdout ID as a Holdout entity object. + """ + 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/optimizely/user_profile.py b/optimizely/user_profile.py index f5ded013e..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 # type: ignore - - 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: diff --git a/optimizely/version.py b/optimizely/version.py index 4f0f20c64..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, 2, 0) +version_info = (5, 8, 0) __version__ = '.'.join(str(v) for v in version_info) 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/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/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/ruff.toml b/ruff.toml new file mode 100644 index 000000000..289c7c599 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,38 @@ +# Ruff configuration +# https://docs.astral.sh/ruff/configuration/ + +line-length = 120 +target-version = "py310" + +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"] diff --git a/setup.py b/setup.py index 1954aa489..8aac986a5 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() @@ -47,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/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)) diff --git a/tests/test_bucketing_holdout.py b/tests/test_bucketing_holdout.py new file mode 100644 index 000000000..8a5e7c78f --- /dev/null +++ b/tests/test_bucketing_holdout.py @@ -0,0 +1,356 @@ +# 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', + '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', + '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_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_cmab_service.py b/tests/test_cmab_service.py index 0b3c593a5..deab77258 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 @@ -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 = { @@ -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", [] ) @@ -70,9 +70,9 @@ 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( + 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", @@ -124,11 +124,11 @@ 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") - 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, @@ -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 @@ -171,17 +171,54 @@ 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", [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"] ) + + 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") diff --git a/tests/test_config.py b/tests/test_config.py index a6e828c2e..29b1c49e3 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1375,3 +1375,482 @@ 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() + + config_body_with_holdouts['holdouts'] = [ + { + 'id': 'holdout_1', + 'key': 'global_holdout', + 'status': 'Running', + 'variations': [], + 'trafficAllocation': [], + 'audienceIds': [] + }, + { + 'id': 'holdout_2', + 'key': 'specific_holdout', + 'status': 'Running', + 'variations': [], + 'trafficAllocation': [], + 'audienceIds': [] + }, + { + 'id': 'holdout_3', + 'key': 'inactive_holdout', + 'status': 'Inactive', + 'variations': [], + 'trafficAllocation': [], + 'audienceIds': [] + } + ] + + 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_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() + + +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_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( + 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) + + + diff --git a/tests/test_config_manager.py b/tests/test_config_manager.py index 56674381b..96bb5ecb9 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) @@ -224,12 +254,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 +325,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' @@ -496,30 +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) - if "Thread for background datafile polling failed. " \ - "Error: timestamp too large to convert to C PyTime_t" not 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. """ diff --git a/tests/test_decision_service.py b/tests/test_decision_service.py index d906a3cfc..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 @@ -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( @@ -1071,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): @@ -1389,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 new file mode 100644 index 000000000..e0f57ecc0 --- /dev/null +++ b/tests/test_decision_service_holdout.py @@ -0,0 +1,2330 @@ +# 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. + +import copy +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 import user_profile +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() + + config_dict_with_holdouts['holdouts'] = [ + { + 'id': 'holdout_1', + 'key': 'test_holdout', + 'status': 'Running', + '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', + '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_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) + + # 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: + # 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, + "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) + + # 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', + '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.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', + '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.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', + '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() + + # 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', + '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.""" + config_dict_with_holdouts = self.config_dict_with_features.copy() + config_dict_with_holdouts['holdouts'] = [ + { + 'id': 'included_holdout', + 'key': 'specific_holdout', + 'status': 'Running', + '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.""" + config_dict_with_holdouts = self.config_dict_with_features.copy() + config_dict_with_holdouts['holdouts'] = [ + { + 'id': 'excluded_holdout', + 'key': 'global_except_one', + 'status': 'Running', + '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.""" + 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', + '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', + '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', + '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', + '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', + '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', + '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 + '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', + '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', + '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', + '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() + + +# --------------------------------------------------------------------------- +# 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, 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() + 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, + ) + + # ------------------------------------------------------------------ + # 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_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. + 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'] + 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_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. + """ + 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) + + decision = result['decision'] + 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 + # ------------------------------------------------------------------ + + 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) + self.assertNotIn('holdout_decisions', result) + + # ------------------------------------------------------------------ + # 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.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.""" + 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.assertNotEqual(result['decision'].source, enums.DecisionSources.HOLDOUT) + self.assertEqual(len(result['holdout_decisions']), 1) + + # ------------------------------------------------------------------ + # 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) + + 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 +# --------------------------------------------------------------------------- + +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_decisions')) + + # ------------------------------------------------------------------ + # 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_decisions')) + + 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.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 + # ------------------------------------------------------------------ + + 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.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 + # ------------------------------------------------------------------ + + 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.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) + # ------------------------------------------------------------------ + + 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_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_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', + ) + 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.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_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_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)], + ) + 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_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, " + "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_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 new file mode 100644 index 000000000..074f4cdeb --- /dev/null +++ b/tests/test_holdout_config.py @@ -0,0 +1,675 @@ +# 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. + +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 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 +""" + +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', + 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)) + + +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_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} + 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 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().""" + + 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( + 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) + 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( + 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') + 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( + 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} + 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( + 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} + 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( + 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( + 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) + 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_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', + '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 (no localHoldouts section) 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_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 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). + + 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() + + 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(), []) + + def test_local_holdouts_missing_included_rules_logged_and_excluded(self): + """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). + """ + 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) + + 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}]) 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() 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: