Assign experiment buckets with a single hash to fix sample ratio mismatch
Role: Data Scientist
Category: Analytics & Experimentation
Difficulty: medium
Interview Round: Other
An experiment used two separate hashes per user, one to decide exposure and one to pick the bucket, and it showed a sample ratio mismatch (SRM). Implement the single-hash fix: hash each user once into an integer `R` in [0, 9999], gate exposure on the high two digits of `R`, and pick the bucket from the low two digits.
```python
def single_hash_assign(user_id: str, salt: str, exposure_rate: float, control_pct: int) -> str:
```
The function must do exactly this:
- `H = int(hashlib.sha256(f"{salt}:{user_id}".encode("utf-8")).hexdigest()[:16], 16)`, using only the first 16 hex characters.
- `R = (H * 10000) // 2**64`, with integer arithmetic only and no floats.
- If `(R // 100) >= round(exposure_rate * 100)`, return `"ignore"`.
- Else, if `(R % 100) < control_pct`, return `"control"`.
- Otherwise return `"treatment"`.
For example, suppose `R == 4237` for some `(salt, user_id)`, with `exposure_rate = 0.50` and `control_pct = 50`:
```text
R // 100 = 42 -> 42 >= round(0.50 * 100) = 50 ? no, so the user is exposed
R % 100 = 37 -> 37 < 50 ? yes
single_hash_assign(...) == "control"
```
```hint Independence
Write `R` as `100 * a + b`. If `R` is uniform on 0 to 9999, what is the joint distribution of `a` and `b`?
```
```hint Rounding
Look at what `exposure_rate * 100` evaluates to in floating point for a value such as 0.57, and at which conversion to an integer keeps the intended threshold.
```
### Constraints & Assumptions
- `exposure_rate` is a fraction in [0, 1].
- `control_pct` is an integer percentage of exposed users, in [0, 100].
- The output is one of `"ignore"`, `"control"` or `"treatment"`, and the same inputs must always give the same output.
### What a Strong Answer Covers
- A function that follows every step exactly: the hash input format, the 16-character slice, the integer projection and both comparisons.
- Why the high and low digits of one uniform `R` give independent exposure and bucket decisions, and how that removes the mismatch.
- How floating point and rounding affect the exposure threshold.
- Behavior at the edge values of `exposure_rate` and `control_pct`, and what happens to existing users when the exposure rate changes.
### Follow-up Questions
- Why did the two-hash approach cause a sample ratio mismatch?
- Why use only the top 64 bits of the digest instead of all 256 bits?
- How would you ramp `exposure_rate` up over time without reshuffling users?
- How would you check a running experiment for a sample ratio mismatch?
Overview: Implement deterministic experiment assignment that hashes each user once with SHA-256, gates exposure on one part of the hash and picks control or treatment from another. It tests integer hashing, float rounding pitfalls and why dependent assignment decisions cause a sample ratio mismatch.