Auditing an A/B Assignment and Free-Trial Trigger Script
Statistics & ExperimentsModel answerLast updated
Review a script that randomly splits users into experiment arms and sends a free-trial offer, then list its bugs and data risks and propose a safer, reproducible design.
Reviewing an experiment assignment job
A growth team runs a small Python job that does two things for a list of users:
- Puts each user into an experiment group, either
controlortreatment. - Sends a free-trial offer to users placed in
treatment.
The script is roughly this:
import random
def assign_and_trigger(users):
assignments = {}
for u in users:
if random.random() < 0.5:
assignments[u["id"]] = "treatment"
send_free_trial(u["email"])
else:
assignments[u["id"]] = "control"
return assignments
The job runs on a schedule, and it can also be retried or re-run manually after a failure.
What to do
- Inspect the script and list the bugs and data-quality risks you can find. Cover randomness, reruns, input data, side effects and analysis.
- Propose concrete refactors or extra checks that make assignment and triggering safe and reproducible.
- Sketch what the improved code or design looks like, and explain how you would monitor the experiment once it is live.
If your own version of the script differs, apply the same checklist to it. State any assumptions you make about the data store and the messaging service.
Hints
Hint 1
Ask what happens if the job runs twice, or crashes halfway through the loop. Which users get a second assignment or a second email?
Hint 2
Replace the call to the random number generator with a function of the experiment name, a salt and the user ID, so the result does not depend on run order or global state.
Hint 3
Separate three steps: validate and deduplicate input, persist the assignment with insert-if-absent semantics, then trigger the offer under an idempotency key. Add logs for assignment and exposure, plus a sample-ratio-mismatch check.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the job as two separate concerns:
- Assignment should be a pure, deterministic function of
(experiment, salt, user_id). - Triggering should be an idempotent side effect, gated on a persisted assignment record.
Everything else is input validation and observability around these two.
Bugs and risks in the script
Randomness and reproducibility
- Unseeded global RNG. Assignments cannot be reproduced or audited, and a backfill gives different groups.
- Seeding is not a real fix.
random.seed(42)ties each user's group to their position in the list, and any other library callingrandomshifts the sequence. - No per-experiment salt. If you move to hashing without a salt, the same users land in treatment in every experiment. Experiments become correlated and results biased.
Idempotency and duplicate exposure
- Reruns reassign users. Someone in control on Monday can be in treatment on Tuesday, which contaminates both arms.
- Duplicate rows in the input send multiple emails, and the dict silently keeps only the last assignment.
- No prior-exposure check. Users who were already assigned, or are already on a trial or paid plan, get the offer again.
- Side effect inside the loop, with nothing persisted. If
send_free_trialraises midway, some users have received the offer but no assignments were saved. A retry re-sends to them.
Data validation
- Null or malformed IDs and mixed types.
123and"123"count as different users, andNonegets a group. - No eligibility filter. Employees, test accounts, existing subscribers and marketing opt-outs are all included.
- Hard-coded split. Changing the ratio means editing code, and nothing records which config produced which assignment.
Observability and analysis
- No assignment or exposure logging. Analysts cannot separate "assigned" from "actually received the offer", so intent-to-treat and treated-only populations get mixed.
- No sample-ratio-mismatch (SRM) check. A skewed split, often from a filter bug, goes unnoticed.
- No timestamp or experiment version. Cohort analysis and clean rollback are impossible.
Refactor
- Deterministic hashing. Compute
bucket = sha256(f"{experiment}:{salt}:{user_id}") mod 10_000and give each arm a contiguous range of buckets. The result is stable across runs, machines and input order, and independent across experiments because of the salt. - Persist, then trigger. Write the assignment with insert-if-absent semantics (a unique key on
(experiment, user_id)). If a row exists, reuse it and never recompute. - Idempotent trigger. Use a key such as
(experiment, user_id, "free_trial"). Mark it sent only after the send succeeds, and have retries skip marked users. If the provider supports idempotency keys, pass the same key to it. - Validate input first. Normalize IDs to
str, strip whitespace, drop nulls, deduplicate, and apply eligibility rules before assignment. - Config-driven. Arm weights, salt, version and trigger arm live in a validated config object (weights must sum to 1).
- Structured logs. Emit separate
assignmentandexposureevents with experiment, version, arm, bucket and timestamp. - SRM check. Run a chi-square goodness-of-fit test of observed arm counts against the configured split and alert at p < 0.001.
Sketch of the improved code
import hashlib, logging
from datetime import datetime, timezone
log = logging.getLogger("experiment")
def bucket_of(name, salt, user_id, buckets=10_000):
h = hashlib.sha256(f"{name}:{salt}:{user_id}".encode()).hexdigest()
return int(h[:15], 16) % buckets
def arm_for(cfg, user_id):
b, cutoff = bucket_of(cfg.name, cfg.salt, user_id, cfg.buckets), 0.0
for arm, w in cfg.arms:
cutoff += w * cfg.buckets
if b < cutoff:
return arm
return cfg.arms[-1][0]
def clean_users(users, is_eligible):
seen, out = set(), []
for u in users:
uid = u.get("id")
if uid is None or str(uid).strip() == "":
continue
uid = str(uid).strip()
if uid in seen:
continue
seen.add(uid)
if is_eligible(u):
out.append({**u, "id": uid})
return out
def assign_and_trigger(users, cfg, store, send_offer, is_eligible=lambda u: True):
counts = {a: 0 for a, _ in cfg.arms}
for u in clean_users(users, is_eligible):
arm = store.get_or_insert((cfg.name, u["id"]), arm_for(cfg, u["id"]))
counts[arm] += 1
log.info({"event": "assignment", "exp": cfg.name, "v": cfg.version,
"user": u["id"], "arm": arm,
"ts": datetime.now(timezone.utc).isoformat()})
if arm != cfg.trigger_arm:
continue
key = (cfg.name, u["id"], "free_trial")
if key in store.sent:
continue
try:
send_offer(u)
except Exception:
log.exception("send failed for %s; will retry next run", u["id"])
continue
store.sent.add(key)
log.info({"event": "exposure", "exp": cfg.name, "user": u["id"]})
return counts
A failed send leaves the assignment saved but the trigger unmarked, so the next run retries only the users who did not get the offer.
Complexity
The job is O(n) in the number of users with O(1) hashing and lookups per user. Memory is O(n) for the dedup set, or O(1) if deduplication is pushed into a database unique constraint.
Trade-offs
- Hash bucketing vs stored random draws. Hashing needs no state to reproduce a result, but you still store assignments for audit and to survive config changes. Storing draws alone is reproducible but harder to scale across services.
- Exactly-once vs at-least-once sending. True exactly-once is not achievable across a network boundary. Mark-after-send with provider-side idempotency keys gives at-least-once with duplicates suppressed. A crash between send and mark can still cause one duplicate, so prefer provider idempotency where available.
- Changing weights mid-experiment. Shifting bucket ranges moves users between arms. Ramp by only extending the treatment range, or start a new experiment version.
Monitoring
- SRM alert on arm counts per run and per day.
- Duplicate-send counter, which should be zero.
- Ratio of assigned to exposed users in treatment, which flags delivery failures.
- Eligibility filter drop rates, since a sudden change usually means an upstream data bug.
Common mistakes
- Seeding the global RNG and calling the job reproducible.
- Hashing the user ID without an experiment salt.
- Sending the email before the assignment is persisted.
- Treating "assigned" and "exposed" as the same event in analysis.
- Ignoring type mismatches in IDs, which silently double-counts users.