1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
# conflict-aware assignment for overlapping A/B tests.
from __future__ import annotations
from typing import Dict, List, Optional, Tuple, Any
import hashlib
from uuid import uuid4
# ---------- Core hashing ----------
def hash_to_bucket(user_id: str, salt: str, modulo: int = 10_000) -> int:
return int(hashlib.sha256(f"{salt}:{user_id}".encode()).hexdigest()[:8], 16) % modulo
def in_allocation(user_id: str, salt: str, pct: float) -> bool:
return hash_to_bucket(user_id, salt) < round(pct * 100)
# ---------- Mutual exclusion (pick one per group) ----------
def choose_exclusive(user_id: str, group_id: str, members: List[Dict[str, Any]]) -> Optional[str]:
total = sum(m.get("weight", 0) for m in members)
if total <= 0:
return None
cut = hash_to_bucket(user_id, f"excl:{group_id}", total)
acc = 0
for m in members:
acc += m["weight"]
if cut < acc:
return m["experiment"]
return None
# ---------- Targeting rules (simple) ----------
def eval_rule(rule: Dict[str, Any], ctx: Dict[str, Any]) -> bool:
# ctx: {"assignments": set[str], "attrs": dict, "triggers": set[str]}
if not rule: return True
if "all" in rule: return all(eval_rule(r, ctx) for r in rule["all"])
if "any" in rule: return any(eval_rule(r, ctx) for r in rule["any"])
if "not" in rule: return not eval_rule(rule["not"], ctx)
if "attrEq" in rule:
k, v = rule["attrEq"]["key"], rule["attrEq"]["val"]
return ctx["attrs"].get(k) == v
if "triggered" in rule: return rule["triggered"] in ctx["triggers"]
if "hasExp" in rule: return rule["hasExp"] in ctx["assignments"]
if "notInExp" in rule: return rule["notInExp"] not in ctx["assignments"]
return True
# ---------- Per-parameter priority merge (higher layers win) ----------
def merge_by_priority(layer_order: List[str], params_by_layer: Dict[str, Dict[str, Any]]
) -> Tuple[Dict[str, Any], List[Dict[str, str]]]:
effective: Dict[str, Any] = {}
overrides: List[Dict[str, str]] = []
for i, layer in enumerate(layer_order): # high -> low
for k, v in (params_by_layer.get(layer) or {}).items():
if k in effective:
winner = next(L for L in layer_order[:i] if k in (params_by_layer.get(L) or {}))
overrides.append({"param": k, "winner_layer": winner, "loser_layer": layer})
continue
effective[k] = v
return effective, overrides
# ---------- Serve path (one request) ----------
def serve_request(user_id: str, namespace_id: str, ctx: Dict[str, Any], cfg: Dict[str, Any]) -> Dict[str, Any]:
ns = next(ns for ns in cfg["product"]["namespaces"] if ns["id"] == namespace_id)
layers: List[str] = ns["layers"] # e.g., ["ranking","ads","ui"]
exps = [e for e in cfg["product"]["experiments"] if e["namespace"] == namespace_id]
groups = [g for g in cfg["product"]["exclusion_groups"] if g["namespace"] == namespace_id]
# 1) Assignment per experiment (after eligibility + trigger)
assignments: Dict[str, str] = {}
for e in exps:
c = {"assignments": set(assignments.values()),
"attrs": ctx.get("attrs", {}), "triggers": set(ctx.get("triggers", []))}
eligible = eval_rule(e.get("eligibility", {}), c)
triggered = (e.get("trigger") in c["triggers"]) if e.get("trigger") else True
if not eligible:
assignments[e["id"]] = "ineligible"
elif not triggered:
assignments[e["id"]] = "none"
else:
salt = f"exp:{e['id']}"
variant = "treatment" if in_allocation(user_id, salt, e["allocation_pct"]) else "control"
assignments[e["id"]] = f"{e['id']}:{variant}"
# 2) Mutual exclusion (keep chosen; mark others excluded)
for g in groups:
chosen = choose_exclusive(user_id, g["id"], g["members"])
if chosen:
for m in g["members"]:
eid = m["experiment"]
if assignments.get(eid, "").startswith(eid) and eid != chosen:
assignments[eid] = "excluded"
# 3) Build params per layer from final assignments
params_by_layer: Dict[str, Dict[str, Any]] = {L: {} for L in layers}
for e in exps:
a = assignments[e["id"]]
if not a.startswith(e["id"]): # ineligible/none/excluded
continue
vname = "treatment" if a.endswith(":treatment") else "control"
for pkey, opts in e.get("parameters", {}).items():
params_by_layer[e["layer"]][pkey] = opts[vname]
# 4) Priority merge + compact exposure log
effective, overrides = merge_by_priority(layers, params_by_layer)
return {
"request_id": str(uuid4()),
"namespace": namespace_id,
"assignments": assignments,
"effective_params": effective,
"override_details": overrides
}
|