Skip to content

Commit daec77d

Browse files
committed
unify weight-vector validation: one rule for bucketing and bandit propensities
1 parent ae3db9a commit daec77d

3 files changed

Lines changed: 70 additions & 68 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
* Consumes the `contextualBandits` payload section (and `encryptedContextualBandits`), evaluates `contextualBanditRef`/`contextualVariations` rules with per-leaf weight substitution, and reports `leafId`, `variationWeights`, and `banditVersion` on experiment results for exposure logging.
99
* New `set_payload()` on `GrowthBook` and `GrowthBookClient` for seeding full SDK payloads; only the sections present are overwritten, and encrypted sections are decrypted with the configured `decryption_key` (JS `setPayload` semantics).
1010
* Payload refreshes missing a section (`savedGroups`, `contextualBandits`) preserve the previous value at every layer instead of wiping it; the synchronous client serializes payload writers and publishes one coherent evaluation snapshot per update (evaluations stay lock-free), matching the async client.
11-
* Malformed bandit definitions or leaves degrade to the rule's aggregate weights instead of raising during evaluation; reported `variationWeights` always match the weights bucketing actually used, and leaf vectors with negative, non-finite, or boolean entries are rejected, and the same strict validation clears unusable aggregate/override vectors on bandit rules (equal weights for both bucketing and metadata).
11+
* Malformed bandit definitions or leaves degrade to the rule's aggregate weights instead of raising during evaluation; reported `variationWeights` always match the weights bucketing actually used, and and a single validity rule now governs every weight vector: `getBucketRanges` normalizes vectors with negative, non-finite, boolean, or non-numeric entries (not just wrong length/sum) to equal weights, so bucket ranges can never be inverted, and bandit leaf/aggregate/override propensities always describe the vector actually used.
1212
* Contextual bandit exposure metadata survives remote evaluation: `rule.tracks` results from the proxy keep `leafId`, `variationWeights`, and `banditVersion` when replayed through the tracking callback.
1313
* Async evaluations that perform I/O (remote eval or a sticky bucket service) freeze every mutable evaluation input — attributes, groups, overrides, forced variations and features, nested containers included — before their first await, so mutating a `UserContext` mid-flight cannot change leaf routing, remote payloads, or forced assignments. Plain CDN evaluations never yield and skip the copy entirely; deferred callbacks get fire-time snapshots in both clients.
1414

‎growthbook/core.py‎

Lines changed: 46 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -516,23 +516,38 @@ def getEqualWeights(numVariations: int) -> List[float]:
516516
WEIGHT_SUM_MAX = 1.01
517517

518518

519+
def _is_valid_weight_vector(weights: Any, num_variations: int) -> bool:
520+
"""The single weight-vector validity rule, shared by bucketing and every
521+
contextual bandit path: a list with one finite, non-negative real number
522+
per variation (booleans excluded), summing to ~1. Anything else is
523+
replaced with equal weights wherever weights are consumed, so bucket
524+
ranges can never be inverted and reported bandit propensities always
525+
describe the vector actually used.
526+
527+
Deliberately stricter than the JS SDK, which checks only length and sum
528+
and will bucket on inverted ranges for e.g. [1.2, -0.2] — corrupt for
529+
assignments and bandit training alike. The divergence exists only for
530+
invalid payloads the server never produces (the shared conformance
531+
corpus exercises none of them)."""
532+
if not isinstance(weights, list) or len(weights) != num_variations:
533+
return False
534+
if not all(
535+
isinstance(w, (int, float))
536+
and not isinstance(w, bool)
537+
and math.isfinite(w)
538+
and w >= 0
539+
for w in weights
540+
):
541+
return False
542+
return WEIGHT_SUM_MIN <= sum(weights) <= WEIGHT_SUM_MAX
543+
544+
519545
def _normalized_weights(numVariations: int, weights: Any) -> List[float]:
520-
"""The weight vector bucketing will actually use: the input when it is a
521-
valid list of the right length whose sum is within tolerance, equal
522-
weights otherwise. Single source of truth shared by getBucketRanges and
523-
the contextual bandit metadata paths, so reported propensities can never
524-
differ from the weights used for bucketing."""
525-
try:
526-
if (
527-
isinstance(weights, list)
528-
and len(weights) == numVariations
529-
and WEIGHT_SUM_MIN <= sum(weights) <= WEIGHT_SUM_MAX
530-
):
531-
return weights
532-
except TypeError:
533-
# Non-numeric entries: fall through to equal weights, like the JS SDK
534-
# (whose length/sum checks silently reject garbage instead of raising).
535-
pass
546+
"""The weight vector bucketing (and bandit metadata) will actually use:
547+
the input when it passes _is_valid_weight_vector, equal weights
548+
otherwise."""
549+
if _is_valid_weight_vector(weights, numVariations):
550+
return cast(List[float], weights)
536551
return getEqualWeights(numVariations)
537552

538553

@@ -624,44 +639,6 @@ def _get_contextual_bandit_leaf(
624639
return None
625640

626641

627-
def _usable_bandit_weights(weights: Any, num_variations: int) -> bool:
628-
"""True only for a leaf weight vector that is safe to substitute for
629-
bucketing: a list with one finite, non-negative number per variation
630-
(booleans excluded), summing to ~1. Anything else is a malformed leaf
631-
and the caller degrades to the aggregate-weights fallback, so reported
632-
propensities always describe a sane vector."""
633-
if not isinstance(weights, list) or len(weights) != num_variations:
634-
return False
635-
if not all(
636-
isinstance(w, (int, float))
637-
and not isinstance(w, bool)
638-
and math.isfinite(w)
639-
and w >= 0
640-
for w in weights
641-
):
642-
return False
643-
return WEIGHT_SUM_MIN <= sum(weights) <= WEIGHT_SUM_MAX
644-
645-
646-
def _sanitize_bandit_experiment_weights(experiment: Experiment[Any]) -> List[float]:
647-
"""Strictly validate a bandit experiment's aggregate weights, clearing
648-
them when unusable, and return the vector bucketing will use.
649-
650-
Contextual-only guard: ordinary experiments keep getBucketRanges'
651-
looser length/sum normalization (JS parity), but a bandit rule must
652-
never bucket on negative ranges or report them as propensities — an
653-
unusable vector is cleared so bucketing and metadata both fall back to
654-
equal weights."""
655-
num_variations = len(experiment.variations)
656-
if experiment.weights is not None and not _usable_bandit_weights(
657-
experiment.weights, num_variations
658-
):
659-
experiment.weights = None
660-
if experiment.weights is None:
661-
return getEqualWeights(num_variations)
662-
return experiment.weights
663-
664-
665642
def _build_contextual_bandit_experiment(
666643
experiment: Experiment[Any],
667644
contextual_bandit_ref: str,
@@ -710,13 +687,13 @@ def _build_contextual_bandit_experiment(
710687

711688
weights = leaf.get("weights") if leaf is not None else None
712689
leaf_id = leaf.get("leafId") if leaf is not None else None
713-
if weights is not None and not _usable_bandit_weights(weights, len(experiment.variations)):
690+
if weights is not None and not _is_valid_weight_vector(weights, len(experiment.variations)):
714691
weights = None
715692
if leaf is not None and (weights is None or leaf_id is None):
716-
# A matched leaf missing its id, or whose weight vector bucketing
717-
# would reject (see _usable_bandit_weights), is a malformed payload;
718-
# degrade to the aggregate-weights fallback rather than reporting
719-
# propensities that differ from the weights actually used.
693+
# A matched leaf missing its id, or whose weight vector fails the
694+
# shared validity rule (see _is_valid_weight_vector), is a malformed
695+
# payload; degrade to the aggregate-weights fallback rather than
696+
# reporting propensities that differ from the weights actually used.
720697
logger.debug(
721698
"Contextual bandit leaf is malformed, feature %s falls back to aggregate weights",
722699
feature_id,
@@ -731,9 +708,11 @@ def _build_contextual_bandit_experiment(
731708
)
732709
cb = {
733710
"leafId": CONTEXTUAL_BANDIT_FALLBACK_LEAF_ID,
734-
# Unusable aggregate weights are cleared so bucketing and the
735-
# reported propensities both degrade to equal weights.
736-
"variationWeights": _sanitize_bandit_experiment_weights(experiment),
711+
# getBucketRanges applies the same normalization, so the reported
712+
# propensities always match the vector bucketing will use.
713+
"variationWeights": _normalized_weights(
714+
len(experiment.variations), experiment.weights
715+
),
737716
}
738717

739718
bandit_version = cb_definition.get("banditVersion")
@@ -1012,12 +991,14 @@ def run_experiment(experiment: Experiment[Any],
1012991
if evalContext.user.overrides.get(experiment.key, None):
1013992
experiment.update(evalContext.user.overrides[experiment.key])
1014993
# Keep reported bandit propensities in sync with the weights actually
1015-
# used for bucketing: an override may have replaced them, and an
1016-
# unusable override vector is cleared (equal weights for both).
994+
# used for bucketing: an override may have replaced them, and
995+
# getBucketRanges normalizes unusable vectors to equal weights.
1017996
if experiment.contextualBandit and experiment.weights is not None:
1018997
synced: ContextualBanditAssignment = {
1019998
"leafId": experiment.contextualBandit["leafId"],
1020-
"variationWeights": _sanitize_bandit_experiment_weights(experiment),
999+
"variationWeights": _normalized_weights(
1000+
len(experiment.variations), experiment.weights
1001+
),
10211002
}
10221003
if "banditVersion" in experiment.contextualBandit:
10231004
synced["banditVersion"] = experiment.contextualBandit["banditVersion"]

‎tests/test_contextual_bandit.py‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -969,8 +969,8 @@ async def mutating_refresh(attributes):
969969
def test_invalid_aggregate_and_override_weights_are_sanitized():
970970
"""Aggregate (fallback) and override weight vectors get the same strict
971971
validation as matched leaves: negative or boolean entries would bucket on
972-
nonsense ranges and report them as propensities, so the vector is cleared
973-
and both bucketing and metadata use equal weights."""
972+
nonsense ranges and report them as propensities, so both bucketing and
973+
the reported metadata normalize them to equal weights."""
974974
for bad_weights in ([1.5, -0.5], [True, False]):
975975
features = {
976976
"bandit-feature": {
@@ -1011,3 +1011,24 @@ def test_invalid_aggregate_and_override_weights_are_sanitized():
10111011
assert res.experimentResult is not None
10121012
assert res.experimentResult.variationWeights == [0.5, 0.5]
10131013
gb.destroy()
1014+
1015+
1016+
def test_bucket_ranges_reject_invalid_weight_vectors():
1017+
"""One weight-validation policy for every experiment: vectors bucketing
1018+
cannot honor sanely (negative, non-finite, boolean, or non-numeric
1019+
entries — not just wrong length/sum) normalize to equal weights, so
1020+
bucket ranges can never be inverted. Deliberately stricter than the JS
1021+
SDK, which checks only length and sum, on these invalid payloads."""
1022+
from growthbook.core import getBucketRanges
1023+
1024+
equal = getBucketRanges(2, 1, None)
1025+
for bad in (
1026+
[1.2, -0.2],
1027+
[True, False],
1028+
[float("inf"), 1.0],
1029+
[float("nan"), 1.0],
1030+
[0.5, "x"],
1031+
):
1032+
assert getBucketRanges(2, 1, bad) == equal, bad
1033+
# Valid vectors are untouched
1034+
assert getBucketRanges(2, 1, [0.4, 0.6]) == [(0, 0.4), (0.4, 1.0)]

0 commit comments

Comments
 (0)