8000 [FSSDK-11184] Update: Send CMAB uuid in impression events by FarhanAnjum-opti · Pull Request #458 · optimizely/python-sdk · GitHub
[go: up one dir, main page]

Skip to content

[FSSDK-11184] Update: Send CMAB uuid in impression events #458

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 48 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
88b4f1e
update: integrate CMAB components into OptimizelyFactory
FarhanAnjum-opti Jun 4, 2025
2563c7b
update: add cmab_service parameter to Optimizely constructor for CMAB…
FarhanAnjum-opti 8000 Jun 4, 2025
fac8946
update: add docstring to DefaultCmabService class for improved docume…
FarhanAnjum-opti Jun 4, 2025
f74bc8c
update: implement CMAB support in bucketer and decision service, reve…
FarhanAnjum-opti Jun 13, 2025
6d1f73d
linting fix
FarhanAnjum-opti Jun 13, 2025
91d53b6
update: add cmab_uuid handling in DecisionService and related tests
FarhanAnjum-opti Jun 16, 2025
3eb755f
- updated function bucket_to_entity_id
FarhanAnjum-opti Jun 16, 2025
a5e4993
update: add None parameter to Decision constructor in user context tests
FarhanAnjum-opti Jun 16, 2025
c1cd97a
update: enhance CMAB decision handling and add related tests
FarhanAnjum-opti Jun 16, 2025
fd7c723
update: fix logger message formatting in CMAB experiment tests
FarhanAnjum-opti Jun 16, 2025
ec19c3b
mypy fix
FarhanAnjum-opti Jun 16, 2025
029262d
update: refine traffic allocation type hints and key naming in bucket…
FarhanAnjum-opti Jun 16, 2025
180fdee
update: remove unused import of cast in bucketer.py
FarhanAnjum-opti Jun 16, 2025
cd5ba39
update: fix return type for numeric_metric_value in get_numeric_value…
FarhanAnjum-opti Jun 16, 2025
92a3258
update: specify type hint for numeric_metric_value in get_numeric_val…
FarhanAnjum-opti Jun 16, 2025
fe100cb
update: fix logger reference in DefaultCmabClient initialization and …
FarhanAnjum-opti Jun 17, 2025
60a4ada
update: enhance error logging for CMAB fetch failures with detailed m…
FarhanAnjum-opti Jun 20, 2025
265d82b
update: enhance decision result handling by introducing VariationResu…
FarhanAnjum-opti Jun 20, 2025
6ca1102
update: refactor get_variation return structure and change tests acco…
FarhanAnjum-opti Jun 20, 2025
c2b3d96
-Error propagated to optimizely.py
FarhanAnjum-opti Jun 23, 2025
0e25622
update: add cmab_uuid parameter to impression events
FarhanAnjum-opti Jun 27, 2025
088f4af
update: add None parameter to impression events in decision tests
FarhanAnjum-opti Jun 27, 2025
b901c5f
update: modify get_variation to return VariationResult and adjust rel…
FarhanAnjum-opti Jun 27, 2025
fa77cca
Merge branch 'farhan-anjum/FSSDK-11175-add-decision-service-methods-f…
FarhanAnjum-opti Jun 27, 2025
d2fc631
update: unit test fixes
FarhanAnjum-opti Jun 27, 2025
752a030
Merge branch 'farhan-anjum/FSSDK-11175-add-decision-service-methods-f…
FarhanAnjum-opti Jun 27, 2025
cbf2c2c
update: include CMAB UUID in activation and add corresponding tests
FarhanAnjum-opti Jun 27, 2025
fdcdfbf
update: add tests for get_variation with and without CMAB UUID
FarhanAnjum-opti Jun 27, 2025
b9a8555
Revert "update: unit test fixes"
FarhanAnjum-opti Jun 30, 2025
a129854
Revert "update: modify get_variation to return VariationResult and ad…
FarhanAnjum-opti Jun 30, 2025
9d63477
Merge branch 'farhan-anjum/FSSDK-11175-add-decision-service-methods-f…
FarhanAnjum-opti Jun 30, 2025
1f7e2a9
update: make cmab_uuid parameter optional in _send_impression_event m…
FarhanAnjum-opti Jun 30, 2025
73a2802
chore: trigger CI by turning on python flag
FarhanAnjum-opti Jun 30, 2025
a6d9771
update: new class method to handle optimizely error decisions
FarhanAnjum-opti Jun 30, 2025
4743376
fix unit test
FarhanAnjum-opti Jun 30, 2025
6d79053
fix: update error logging format for CMAB fetch failures
FarhanAnjum-opti Jun 30, 2025
3c903c7
chore: trigger CI
FarhanAnjum-opti Jul 1, 2025
c637878
update: enhance decision service to handle error states and improve b…
FarhanAnjum-opti Jul 3, 2025
62bbf64
Merge branch 'farhan-anjum/FSSDK-11175-add-decision-service-methods-f…
FarhanAnjum-opti Jul 3, 2025
0bc4fbd
update: remove debug print statement from Optimizely class
FarhanAnjum-opti Jul 3, 2025
8668565
Merge branch 'farhan-anjum/FSSDK-11175-add-decision-service-methods-f…
FarhanAnjum-opti Jul 3, 2025
fcdad1f
update: enhance bucketing logic to support CMAB traffic allocations
FarhanAnjum-opti Jul 3, 2025
dd4790d
Merge branch 'farhan-anjum/FSSDK-11175-add-decision-service-methods-f…
FarhanAnjum-opti Jul 3, 2025
aca7df4
update: improve error logging for CMAB decision fetch failures
FarhanAnjum-opti Jul 3, 2025
c14b768
Merge branch 'farhan-anjum/FSSDK-11175-add-decision-service-methods-f…
FarhanAnjum-opti Jul 3, 2025
72955a0
update: improve logging and error handling in bucketer and decision s…
FarhanAnjum-opti Jul 7, 2025
265ea3c
Merge branch 'farhan-anjum/FSSDK-11175-add-decision-service-methods-f…
FarhanAnjum-opti Jul 7, 2025
b88c08b
Merge branch 'master' into farhan-anjum/FSSDK-11184-update-impression…
FarhanAnjum-opti Jul 7, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 30 additions & 74 deletions optimizely/bucketer.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
if TYPE_CHECKING:
# prevent circular dependenacy by skipping import at runtime
from .project_config import ProjectConfig
from .entities import Experiment, Variation, Group
from .entities import Experiment, Variation
from .helpers.types import TrafficAllocation


Expand Down Expand Up @@ -119,6 +119,34 @@ 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

elif not decide_reasons:
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
) -> tuple[Optional[str], list[str]]:
"""
For a given experiment and bucketing ID determines variation ID to be shown to user.

Args:
project_config: Instance of ProjectConfig.
experiment: The experiment object (used for group/groupPolicy logic if needed).
user_id: The user ID string.
bucketing_id: The bucketing ID string for the user.

Returns:
Tuple of (entity_id or None, list of decide reasons).
"""
decide_reasons: list[str] = []
if not experiment:
return None, decide_reasons
Expand Down Expand Up @@ -154,77 +182,5 @@ def bucket(
# Bucket user if not in white-list and in group (if any)
variation_id = self.find_bucket(project_config, bucketing_id,
experiment.id, experiment.trafficAllocation)
if variation_id:
variation = project_config.get_variation_from_id_by_experiment_id(experiment.id, variation_id)
return variation, decide_reasons

else:
message = 'Bucketed into an empty traffic range. Returning nil.'
project_config.logger.info(message)
decide_reasons.append(message)

return None, decide_reasons

def bucket_to_entity_id(
self,
bucketing_id: str,
experiment: Experiment,
traffic_allocations: list[TrafficAllocation],
group: Optional[Group] = None
) -> tuple[Optional[str], list[str]]:
"""
Buckets the user and returns the entity ID (for CMAB experiments).
Args:
bucketing_id: The bucketing ID string for the user.
experiment: The experiment object (for group/groupPolicy logic if needed).
traffic_allocations: List of traffic allocation dicts (should have 'entity_id' and 'end_of_range' keys).
group: (optional) Group object for mutex group support.

Returns:
Tuple of (entity_id or None, list of decide reasons).
"""
decide_reasons = []

group_id = getattr(experiment, 'groupId', None)
if group_id and group and getattr(group, 'policy', None) == 'random':
bucket_key = bucketing_id + group_id
bucket_val = self._generate_bucket_value(bucket_key)
decide_reasons.append(f'Generated group bucket value {bucket_val} for key "{bucket_key}".')

matched = False
for allocation in group.trafficAllocation:
end_of_range = allocation['endOfRange']
entity_id = allocation['entityId']
if bucket_val < end_of_range:
matched = True
if entity_id != experiment.id:
decide_reasons.append(
f'User not bucketed into experiment "{experiment.id}" (got "{entity_id}").'
)
return None, decide_reasons
decide_reasons.append(
f'User is bucketed into experiment "{experiment.id}" within group "{group_id}".'
)
break
if not matched:
decide_reasons.append(
f'User not bucketed into any experiment in group "{group_id}".'
)
return None, decide_reasons

# Main experiment bucketing
bucket_key = bucketing_id + experiment.id
bucket_val = self._generate_bucket_value(bucket_key)
decide_reasons.append(f'Generated experiment bucket value {bucket_val} for key "{bucket_key}".')

for allocation in traffic_allocations:
end_of_range = allocation['endOfRange']
entity_id = allocation['entityId']
if bucket_val < end_of_range:
decide_reasons.append(
f'User bucketed into entity id "{entity_id}".'
)
return entity_id, decide_reasons

decide_reasons.append('User not bucketed into any entity id.')
return None, decide_reasons
return variation_id, decide_reasons
2 changes: 0 additions & 2 deletions optimizely/decision/optimizely_decision.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,10 @@ def as_json(self) -> dict[str, Any]:
@classmethod
def new_error_decision(cls, key: str, user: OptimizelyUserContext, reasons: list[str]) -> OptimizelyDecision:
"""Create a new OptimizelyDecision representing an error state.

Args:
key: The flag key
user: The user context
reasons: List of reasons explaining the error

Returns:
OptimizelyDecision with error state values
"""
Expand Down
66 changes: 32 additions & 34 deletions optimizely/decision_service.py
< 23DA td class="blob-code blob-code-addition js-file-line">
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
# prevent circular dependenacy by skipping import at runtime
from .project_config import ProjectConfig
from .logger import Logger
from .helpers.types import TrafficAllocation


class CmabDecisionResult(TypedDict):
Expand Down Expand Up @@ -134,6 +133,7 @@ def _get_decision_for_cmab_experiment(
project_config: ProjectConfig,
experiment: entities.Experiment,
user_context: OptimizelyUserContext,
bucketing_id: str,
options: Optional[Sequence[str]] = None
) -> CmabDecisionResult:
"""
Expand All @@ -143,14 +143,36 @@ def _get_decision_for_cmab_experiment(
project_config: Instance of ProjectConfig.
experiment: The experiment object for which the decision is to be made.
user_context: The user context containing user id and attributes.
bucketing_id: The bucketing ID to use for traffic allocation.
options: Optional sequence of decide options.

Returns:
A dictionary containing:
- "error": Boolean indicating if there was an error.
- "result": The CmabDecision result or empty dict if error.
- "result": The CmabDecision result or None if error.
- "reasons": List of strings with reasons or error messages.
"""
decide_reasons: list[str] = []
user_id = user_context.user_id

# Check if user is in CMAB traffic allocation
bucketed_entity_id, bucket_reasons = self.bucketer.bucket_to_entity_id(
project_config, experiment, user_id, bucketing_id
)
decide_reasons.extend(bucket_reasons)

if not bucketed_entity_id:
message = f'User "{user_context.user_id}" not in CMAB experiment ' \
f'"{experiment.key}" due to traffic allocation.'
self.logger.info(message)
decide_reasons.append(message)
return {
"error": False,
"result": None,
"reasons": decide_reasons,
}
# 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(
Expand All @@ -159,7 +181,7 @@ def _get_decision_for_cmab_experiment(
return {
"error": False,
"result": cmab_decision,
"reasons": [],
"reasons": decide_reasons,
}
except Exception as e:
error_message = Errors.CMAB_FETCH_FAILED_DETAILED.format(experiment.key)
Expand Down Expand Up @@ -465,49 +487,25 @@ def get_variation(
# If so, handle CMAB-specific traffic allocation and decision logic.
# Otherwise, proceed with standard bucketing logic for non-CMAB experiments.
if experiment.cmab:
CMAB_DUMMY_ENTITY_ID = "$"
# Build the CMAB-specific traffic allocation
cmab_traffic_allocation: list[TrafficAllocation] = [{
"entityId": CMAB_DUMMY_ENTITY_ID,
"endOfRange": experiment.cmab['trafficAllocation']
}]

# Check if user is in CMAB traffic allocation
group = None
if experiment.groupId:
group = project_config.get_group(group_id=experiment.groupId)
bucketed_entity_id, bucket_reasons = self.bucketer.bucket_to_entity_id(
bucketing_id, experiment, cmab_traffic_allocation, group
)
decide_reasons += bucket_reasons
if bucketed_entity_id != CMAB_DUMMY_ENTITY_ID:
message = f'User "{user_id}" not in CMAB experiment "{experiment.key}" due to traffic allocation.'
self.logger.info(message)
decide_reasons.append(message)
return {
'cmab_uuid': None,
'error': False,
'reasons': decide_reasons,
'variation': None
}

# User is in CMAB allocation, proceed to CMAB decision
experiment.cmab
cmab_decision_result = self._get_decision_for_cmab_experiment(project_config,
experiment,
user_context,
bucketing_id,
options)
decide_reasons += cmab_decision_result.get('reasons', [])
cmab_decision = cmab_decision_result.get('result')
if not cmab_decision or cmab_decision_result['error']:
if cmab_decision_result['error']:
return {
'cmab_uuid': None,
'error': True,
'reasons': decide_reasons,
'variation': None
}
variation_id = cmab_decision['variation_id']
cmab_uuid = cmab_decision['cmab_uuid']
variation = project_config.get_variation_from_id(experiment_key=experiment.key, variation_id=variation_id)
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,
variation_id=variation_id) if variation_id else None
else:
# Bucket the user
variation, bucket_reasons = self.bucketer.bucket(project_config, experiment, user_id, bucketing_id)
Expand Down
2 changes: 1 addition & 1 deletion optimizely/optimizely.py
Original file line number Diff line number Diff line change
Expand Up @@ -1376,7 +1376,7 @@ def _decide_for_keys(
user_context,
merged_decide_options
)

print("here")
for i in range(0, len(flags_without_forced_decision)):
decision = decision_list[i]['decision']
reasons = decision_list[i]['reasons']
Expand Down
Loading
0