Skip to content

Commit 06d9dc4

Browse files
committed
validate bandit leaf weight vectors before substituting them for bucketing
1 parent 0c00c70 commit 06d9dc4

2 files changed

Lines changed: 46 additions & 5 deletions

File tree

‎growthbook/core.py‎

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
513520
def 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+
600621
def _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,

‎tests/test_contextual_bandit.py‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -437,7 +437,24 @@ def test_malformed_bandit_payload_degrades_gracefully():
437437
missing_leaf_id = {
438438
"cb-bandit": {"contexts": [{"condition": {}, "weights": [1, 0]}]}
439439
}
440-
for bad_map in (missing_weights, missing_leaf_id, {"cb-bandit": [1, 2]}, {"cb-bandit": {}}):
440+
441+
def leaf_weights(weights):
442+
return {"cb-bandit": {"contexts": [{"leafId": 1, "condition": {}, "weights": weights}]}}
443+
444+
for bad_map in (
445+
missing_weights,
446+
missing_leaf_id,
447+
{"cb-bandit": [1, 2]},
448+
{"cb-bandit": {}},
449+
# Weight vectors that bucketing would reject (or crash on) are
450+
# treated as malformed leaves, so reported propensities always match
451+
# the weights actually used.
452+
leaf_weights("ab"), # not a list
453+
leaf_weights(5), # not sized
454+
leaf_weights([1, 0, 0]), # wrong length for 2 variations
455+
leaf_weights([1, "x"]), # non-numeric entry
456+
leaf_weights([0.9, 0.9]), # sum outside bucketing tolerance
457+
):
441458
gb = GrowthBook(attributes={"id": "1"}, features=CB_FEATURES, contextualBandits=bad_map)
442459
res = gb.eval_feature("bandit-feature")
443460
assert res.experimentResult.leafId == -1

0 commit comments

Comments
 (0)