@@ -510,6 +510,13 @@ def getEqualWeights(numVariations: int) -> List[float]:
510510 return [1 / numVariations for _ in range (numVariations )]
511511
512512
513+ # Weight vectors whose sum falls outside this tolerance are replaced with
514+ # equal weights at bucketing time (shared with the contextual bandit leaf
515+ # validation, which must reject exactly what bucketing would reject).
516+ WEIGHT_SUM_MIN = 0.99
517+ WEIGHT_SUM_MAX = 1.01
518+
519+
513520def getBucketRanges (
514521 numVariations : int , coverage : float = 1 , weights : Optional [List [float ]] = None
515522) -> List [Tuple [float , float ]]:
@@ -521,7 +528,7 @@ def getBucketRanges(
521528 weights = getEqualWeights (numVariations )
522529 if len (weights ) != numVariations :
523530 weights = getEqualWeights (numVariations )
524- if sum (weights ) < 0.99 or sum (weights ) > 1.01 :
531+ if sum (weights ) < WEIGHT_SUM_MIN or sum (weights ) > WEIGHT_SUM_MAX :
525532 weights = getEqualWeights (numVariations )
526533
527534 cumulative : float = 0
@@ -597,6 +604,20 @@ def _get_contextual_bandit_leaf(
597604 return None
598605
599606
607+ def _usable_bandit_weights (weights : Any , num_variations : int ) -> bool :
608+ """True only for a leaf weight vector that getBucketRanges will honor
609+ as-is: a list of numbers, one per variation, summing to ~1. Anything else
610+ would be silently replaced with equal weights at bucketing time (or crash
611+ len()/sum() on non-list payloads), so reporting it as the assignment
612+ propensities would be wrong — the caller degrades to the
613+ aggregate-weights fallback instead."""
614+ if not isinstance (weights , list ) or len (weights ) != num_variations :
615+ return False
616+ if not all (isinstance (w , (int , float )) for w in weights ):
617+ return False
618+ return WEIGHT_SUM_MIN <= sum (weights ) <= WEIGHT_SUM_MAX
619+
620+
600621def _build_contextual_bandit_experiment (
601622 experiment : Experiment [Any ],
602623 contextual_bandit_ref : str ,
@@ -645,10 +666,13 @@ def _build_contextual_bandit_experiment(
645666
646667 weights = leaf .get ("weights" ) if leaf is not None else None
647668 leaf_id = leaf .get ("leafId" ) if leaf is not None else None
669+ if weights is not None and not _usable_bandit_weights (weights , len (experiment .variations )):
670+ weights = None
648671 if leaf is not None and (weights is None or leaf_id is None ):
649- # A matched leaf missing its weights or id is a malformed payload;
650- # degrade to the aggregate-weights fallback rather than bucketing on
651- # partial data.
672+ # A matched leaf missing its id, or whose weight vector bucketing
673+ # would reject (see _usable_bandit_weights), is a malformed payload;
674+ # degrade to the aggregate-weights fallback rather than reporting
675+ # propensities that differ from the weights actually used.
652676 logger .debug (
653677 "Contextual bandit leaf is malformed, feature %s falls back to aggregate weights" ,
654678 feature_id ,
0 commit comments