Skip to content

Commit d769d7b

Browse files
committed
validate rule.tracks bandit metadata with the local evaluation rules
1 parent ce7bff8 commit d769d7b

3 files changed

Lines changed: 80 additions & 10 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
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.
1111
* 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 a single, total validity rule governs every weight vector: `getBucketRanges` normalizes vectors with negative, non-finite, boolean, non-numeric, or float-overflowing entries (not just wrong length/sum) to equal weights — never raising, even on arbitrary-precision integers, so bucket ranges can never be inverted, and bandit leaf/aggregate/override propensities always describe the vector actually used. Bandit identifiers get the same treatment: a leaf with a non-integer `leafId` is malformed (aggregate-weights fallback), and a non-integer `banditVersion` is omitted, so exposure metadata never carries invalid attribution ids into bandit training. A rule that pairs `contextualBanditRef` with explicit `ranges` buckets on the ranges (unchanged, matching the JS SDK) but drops the bandit metadata, since leaf propensities cannot describe a ranges-governed assignment.
12-
* Contextual bandit exposure metadata survives remote evaluation: `rule.tracks` results from the proxy keep `leafId`, `variationWeights`, and `banditVersion` when replayed through the tracking callback.
12+
* Contextual bandit exposure metadata survives remote evaluation: `rule.tracks` results from the proxy keep `leafId`, `variationWeights`, and `banditVersion` when replayed through the tracking callback, held to the same validity rules as locally evaluated exposures (invalid identifiers or weight vectors are dropped, not forwarded).
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. `preload_remote_eval` takes the same call-time snapshot, so mutating the context after preloading can no longer cache one attribute state's response under another's key via the stale-while-revalidate background refresh.
1414

1515
### Bug Fixes

‎growthbook/core.py‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -606,6 +606,20 @@ def _fire_rule_tracks(
606606
try:
607607
# Experiment accepts **_ignored, so passing the raw proxy dict is safe.
608608
experiment = Experiment(**exp_data)
609+
# Contextual bandit exposure metadata evaluated by the proxy is
610+
# payload data like any other: hold it to the same validity rules
611+
# as local evaluation (the JS SDK passes it through verbatim). An
612+
# invalid leafId or weight vector drops all bandit metadata; an
613+
# invalid banditVersion drops just that field.
614+
leaf_id = res_data.get("leafId")
615+
variation_weights = res_data.get("variationWeights")
616+
bandit_version = res_data.get("banditVersion")
617+
if not _is_valid_bandit_id(leaf_id) or not _is_valid_weight_vector(
618+
variation_weights, len(experiment.variations)
619+
):
620+
leaf_id = variation_weights = bandit_version = None
621+
elif not _is_valid_bandit_id(bandit_version):
622+
bandit_version = None
609623
result = Result(
610624
variationId=res_data.get("variationId", 0),
611625
inExperiment=res_data.get("inExperiment", False),
@@ -617,12 +631,9 @@ def _fire_rule_tracks(
617631
meta=meta,
618632
bucket=res_data.get("bucket"),
619633
stickyBucketUsed=res_data.get("stickyBucketUsed", False),
620-
# Contextual bandit exposure metadata evaluated by the proxy.
621-
# The JS SDK passes the proxy result through verbatim, so
622-
# these must survive the reconstruction too.
623-
leafId=res_data.get("leafId"),
624-
variationWeights=res_data.get("variationWeights"),
625-
banditVersion=res_data.get("banditVersion"),
634+
leafId=leaf_id,
635+
variationWeights=variation_weights,
636+
banditVersion=bandit_version,
626637
)
627638
tracking_cb(experiment, result, eval_context.user)
628639
except Exception:

‎tests/test_contextual_bandit.py‎

Lines changed: 62 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -596,9 +596,10 @@ def test_failed_bandit_decryption_preserves_previous_map():
596596

597597

598598
def test_remote_eval_tracks_preserve_bandit_fields():
599-
"""rule.tracks entries from the remote-eval proxy must reach the tracking
600-
callback with their contextual bandit fields intact — the JS SDK passes
601-
the proxy result through verbatim."""
599+
"""Valid rule.tracks entries from the remote-eval proxy must reach the
600+
tracking callback with their contextual bandit fields intact (the JS SDK
601+
passes the proxy result through verbatim; Python additionally validates —
602+
see test_remote_eval_tracks_drop_invalid_bandit_fields)."""
602603
tracked = []
603604

604605
def on_view(experiment, result, user_context):
@@ -647,6 +648,64 @@ def on_view(experiment, result, user_context):
647648
gb.destroy()
648649

649650

651+
@pytest.mark.parametrize(
652+
"extras,expected",
653+
[
654+
# Invalid leafId drops all bandit metadata.
655+
({"leafId": "8", "variationWeights": [0.2, 0.8], "banditVersion": 7},
656+
(None, None, None)),
657+
# Invalid weight vector drops all bandit metadata.
658+
({"leafId": 8, "variationWeights": [1.2, -0.2], "banditVersion": 7},
659+
(None, None, None)),
660+
# Invalid banditVersion drops just that field.
661+
({"leafId": 8, "variationWeights": [0.2, 0.8], "banditVersion": True},
662+
(8, [0.2, 0.8], None)),
663+
],
664+
)
665+
def test_remote_eval_tracks_drop_invalid_bandit_fields(extras, expected):
666+
"""Proxy rule.tracks metadata is payload data and gets the same validity
667+
rules as local evaluation, so remote-eval exposures can't feed corrupt
668+
identifiers or propensities into bandit training either."""
669+
tracked = []
670+
671+
def on_view(experiment, result, user_context):
672+
tracked.append(result)
673+
674+
result_data = {
675+
"variationId": 1,
676+
"inExperiment": True,
677+
"hashUsed": True,
678+
"hashAttribute": "id",
679+
"hashValue": "1",
680+
"value": "treatment",
681+
**extras,
682+
}
683+
gb = GrowthBook(
684+
attributes={"id": "1"},
685+
on_experiment_viewed=on_view,
686+
features={
687+
"remote-feature": {
688+
"defaultValue": "x",
689+
"rules": [{
690+
"force": "treatment",
691+
"tracks": [{
692+
"experiment": {
693+
"key": "bandit-exp",
694+
"variations": ["control", "treatment"],
695+
},
696+
"result": result_data,
697+
}],
698+
}],
699+
}
700+
},
701+
)
702+
gb.eval_feature("remote-feature")
703+
assert len(tracked) == 1
704+
r = tracked[0]
705+
assert (r.leafId, r.variationWeights, r.banditVersion) == expected
706+
gb.destroy()
707+
708+
650709
@pytest.mark.asyncio
651710
async def test_async_remote_eval_tracks_preserve_bandit_fields():
652711
tracked = []

0 commit comments

Comments
 (0)