Assign users to experiment variants with salted hash bucketing
Why it matters Experiment platforms for ranking models and LLM prompts use salted hashing to assign users consistently.
An online experiment must show each user the same variant every time, without storing assignments, and different experiments must split users independently.
Write assign_variants(user_ids, experiment, variants). variants is a list of (name, weight) with positive weights. For each user:
- key = experiment + ":" + str(user_id)
- h = int(hashlib.md5(key.encode()).hexdigest()[:8], 16) / 2 ** 32, a number in [0, 1)
- cumulative = running sum of weights divided by the total weight; pick the first variant with h < cumulative.
Return the list of variant names in user order.
def assign_variants(user_ids, experiment, variants)Example
assign_variants([1, 2, 3, 4, 5], "price_test", [("control", 1), ("treat", 1)]) gives ['control', 'control', 'control', 'treat', 'treat'].
Understand the idea
To run an A/B test you must split users into groups that are random, stable (a user never flips between groups) and independent across experiments. Storing every assignment is costly. Instead, hash the user id: a good hash behaves like a random number but always gives the same value for the same input.
Example: hashing "price_test:1" gives about 0.281, below the 0.5 cut, so user 1 gets control. User 4 hashes to about 0.975 and gets treat. For a different experiment "new_ranker", user 1 hashes to 0.874 instead, so the two experiments split users differently.
Rule: h = int(md5(experiment + ":" + user)[:8], 16) / 2^32; variant = first i with h < cumulative_weight_i / total.
Salting by experiment name is what keeps one test's treatment group from also being another test's treatment group.