Module: Shipeasy::SDK::Eval

Defined in:
lib/shipeasy/sdk/eval.rb

Defined Under Namespace

Classes: Assignment, ExperimentResult

Class Method Summary collapse

Class Method Details

.bucket_hit(pct, uid, salt) ⇒ Object

Hash the caller into [0, 10000) and test against pct. No-unit contract (experiment-platform/18): a fully-rolled bucket is on for everyone without a unit id; a fractional one needs a stable unit, so it is off. Mirrors core's bucketHit.



110
111
112
113
114
115
# File 'lib/shipeasy/sdk/eval.rb', line 110

def self.bucket_hit(pct, uid, salt)
  return false if pct <= 0
  return pct >= 10000 if uid.nil? || uid.to_s.empty?
  return true if pct >= 10000
  murmur3("#{salt}:#{uid}") % 10000 < pct
end

.clamp_pct(n) ⇒ Object



73
74
75
76
77
# File 'lib/shipeasy/sdk/eval.rb', line 73

def self.clamp_pct(n)
  return 0 if n < 0
  return 10000 if n > 10000
  n
end

.effective_pct(entry, now) ⇒ Object

Effective rollout % for a stack entry at time now (epoch ms). A condition with no explicit rolloutPct defaults to 100% (match => pass); a rollout to 0%. A ramp linearly interpolates from=>to over [startAt, startAt + durationMs] via truncating-toward-zero division — the cross-SDK contract (experiment-platform/04-evaluation.md). Mirrors core's effectivePct.



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/shipeasy/sdk/eval.rb', line 85

def self.effective_pct(entry, now)
  type = entry["type"] || entry[:type]
  raw  = entry["rolloutPct"] || entry[:rolloutPct]
  base = raw.nil? ? (type == "condition" ? 10000 : 0) : raw
  ramp = entry["ramp"] || entry[:ramp]
  return base unless ramp

  from      = ramp["from"] || ramp[:from]
  to        = ramp["to"] || ramp[:to]
  start_at  = ramp["startAt"] || ramp[:startAt]
  duration  = ramp["durationMs"] || ramp[:durationMs]
  return from if now <= start_at
  return to if now >= start_at + duration

  delta   = to - from # signed
  elapsed = now - start_at
  # .to_i on the float quotient truncates toward zero (works for a negative
  # ramp-down delta, unlike Ruby's floor-division integer `/`).
  clamp_pct(from + (delta * elapsed).fdiv(duration).to_i)
end

.enabled?(v) ⇒ Boolean

Returns:

  • (Boolean)


10
11
12
# File 'lib/shipeasy/sdk/eval.rb', line 10

def self.enabled?(v)
  v == 1 || v == true
end

.eval_experiment(exp, flags_blob, exps_blob, user, exp_name: nil, sticky_store: nil) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/shipeasy/sdk/eval.rb', line 242

def self.eval_experiment(exp, flags_blob, exps_blob, user, exp_name: nil, sticky_store: nil)
  universe_name  = exp && exp["universe"]
  universe       = exps_blob&.dig("universes", universe_name)
  param_defaults = param_defaults_from_schema(universe && (universe["param_schema"] || universe[:param_schema]))

  not_in = ExperimentResult.new(in_experiment: false, group: "control", params: nil)
  as_group = lambda do |g|
    ExperimentResult.new(
      in_experiment: true, group: g["name"], params: merge_params(param_defaults, g["params"]),
    )
  end

  return not_in unless exp && exp["status"] == "running"

  targeting_gate = exp["targetingGate"]
  if targeting_gate && !targeting_gate.empty?
    gate = flags_blob&.dig("gates", targeting_gate)
    return not_in unless gate && eval_gate(gate, user)
  end

  bucket_by = exp["bucketBy"] || exp[:bucketBy]
  uid = pick_identifier(user, bucket_by)
  return not_in unless uid

  # One segment in the universe's shared [0, 10000) hash space. The holdout
  # carve-out AND every experiment's pool slice are disjoint ranges of THIS
  # segment — that's what makes "held out / taken / free" a real partition.
  universe_seg = murmur3("#{universe_name}:#{uid}") % 10000

  holdout = universe&.dig("holdout_range")
  if holdout
    return not_in if universe_seg >= holdout[0] && universe_seg <= holdout[1]
  end

  # Holdout gate: a passing gate holds the unit out of every experiment in
  # the universe (mirrors the universe carve-out, but gate-driven).
  holdout_gate = exp["holdoutGate"]
  if holdout_gate && !holdout_gate.to_s.empty?
    gate = flags_blob&.dig("gates", holdout_gate)
    return not_in if gate && eval_gate(gate, user)
  end

  salt          = exp["salt"]
  allocation_pct = exp["allocationPct"] || 0
  groups = exp["groups"] || []
  salt8 = (salt || "")[0, 8]

  # Durable overrides (spec step 1, forced-but-gated). Reached only after the
  # unit passes targeting and is not held out, so an override may now pin the
  # group — bypassing allocation + the weighted pick but NOT the gates above.
  # ID overrides (tier 1) beat cohort/GK overrides (tier 2); a forced group
  # that no longer exists falls through to normal allocation. No-op when
  # unconfigured, so v1/v2 stay byte-identical. Mirrors @shipeasy/core.
  forced = resolve_forced_group(exp, uid, flags_blob, user)
  if forced
    g = groups.find { |x| x["name"] == forced }
    if g
      sticky_store.set(uid, exp_name, { "g" => forced, "s" => salt8 }) if sticky_store && exp_name
      return as_group.call(g)
    end
  end

  # Sticky short-circuit: an enrolled unit whose stored salt prefix still
  # matches skips allocation and returns the stored group. If the stored
  # group no longer exists, fall through to re-bucket + overwrite.
  if sticky_store && exp_name
    entry = (sticky_store.get(uid) || {})[exp_name]
    if entry && entry["s"] == salt8
      g = groups.find { |x| x["name"] == entry["g"] }
      return as_group.call(g) if g
    end
  end

  # Allocation. Pooled (hashVersion >= 2 with a slice) gives real mutual
  # exclusion: the unit's universe segment must fall in the claimed range.
  # Legacy falls back to an independent per-experiment salt so siblings
  # overlap freely (the existing parity path).
  hash_version = exp["hashVersion"] || exp[:hashVersion] || 1
  pool_offset  = exp["poolOffsetBp"] || exp[:poolOffsetBp]
  pool_size    = exp["poolSizeBp"] || exp[:poolSizeBp]
  pooled       = hash_version >= 2 && !pool_offset.nil? && !pool_size.nil? && pool_size > 0
  if pooled
    lo = pool_offset
    hi = pool_offset + pool_size
    return not_in if universe_seg < lo || universe_seg >= hi
  else
    return not_in if murmur3("#{salt}:alloc:#{uid}") % 10000 >= allocation_pct
  end

  # Group split over [0, usable) where usable = 10000 - reserved; a unit in
  # the reserved tail is left unassigned so an appended variant can absorb it.
  reserved = (exp["reservedHeadroomBp"] || exp[:reservedHeadroomBp] || 0)
  reserved = 0 if reserved < 0
  reserved = 10000 if reserved > 10000
  usable = 10000 - reserved
  group_hash = murmur3("#{salt}:group:#{uid}") % 10000
  return not_in if group_hash >= usable

  cumulative = 0
  groups.each_with_index do |g, i|
    cumulative += g["weight"]
    if group_hash < cumulative || i == groups.length - 1
      sticky_store.set(uid, exp_name, { "g" => g["name"], "s" => salt8 }) if sticky_store && exp_name
      return as_group.call(g)
    end
  end

  not_in
end

.eval_gate(gate, user) ⇒ Object



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/shipeasy/sdk/eval.rb', line 149

def self.eval_gate(gate, user)
  return false if enabled?(gate["killswitch"])
  return false unless enabled?(gate["enabled"])

  # Modern gatekeepers ship an ordered `stack`; evaluate it top-to-bottom and
  # pass on the first entry whose rules match AND whose bucket hits. This is
  # the canonical model — the flat `rules`/`rolloutPct` below are a lossy
  # approximation (a whitelist condition at 100% collapses to `rolloutPct: 0`
  # once the public rollout is 0%, which the flat path would wrongly read as
  # "never"). Mirrors @shipeasy/core evalGatekeeper — keep the two in sync.
  stack = gate["stack"] || gate[:stack]
  if stack.is_a?(Array) && !stack.empty?
    now = (Time.now.to_f * 1000).to_i
    gate_salt = gate["salt"] || gate[:salt]
    stack.each do |entry|
      return true if eval_stack_entry(entry, user, gate_salt, now)
    end
    return false
  end

  (gate["rules"] || []).each do |rule|
    return false unless match_rule(rule, user)
  end

  uid = user["user_id"] || user[:user_id] || user["anonymous_id"] || user[:anonymous_id]
  # No unit id (an unidentified request before any anon id is minted): a
  # fully-rolled gate is on for everyone, so it can be answered without
  # bucketing; a fractional rollout genuinely needs a stable unit, so deny
  # until one exists. Rules above are still checked, so targeting wins.
  # See experiment-platform/18-identity-bucketing.md.
  return (gate["rolloutPct"] || gate[:rolloutPct] || 0) >= 10000 unless uid

  salt = gate["salt"] || gate[:salt]
  murmur3("#{salt}:#{uid}") % 10000 < (gate["rolloutPct"] || gate[:rolloutPct] || 0)
end

.eval_stack_entry(entry, user, fallback_salt, now) ⇒ Object

Evaluate one gatekeeper stack entry. A condition gates on its rules (pass: "all" | "any") then buckets at its own rollout % (default 100%); a rollout buckets everyone who reached it (default 0%). A condition's default bucketing salt is its own id so each step buckets independently; a rollout falls back to the gate salt so existing entries don't re-bucket. Mirrors core's evalStackEntry.



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/shipeasy/sdk/eval.rb', line 123

def self.eval_stack_entry(entry, user, fallback_salt, now)
  type = entry["type"] || entry[:type]
  bucket_by = entry["bucketBy"] || entry[:bucketBy]
  entry_salt = entry["salt"] || entry[:salt]

  if type == "condition"
    rules = entry["rules"] || entry[:rules] || []
    return false if rules.empty?

    mode = entry["pass"] || entry[:pass] || "all"
    matched =
      if mode == "any"
        rules.any? { |r| match_rule(r, user) }
      else
        rules.all? { |r| match_rule(r, user) }
      end
    return false unless matched

    salt = (entry_salt && !entry_salt.to_s.empty?) ? entry_salt : (entry["id"] || entry[:id] || fallback_salt)
    bucket_hit(effective_pct(entry, now), pick_identifier(user, bucket_by), salt)
  else
    salt = (entry_salt && !entry_salt.to_s.empty?) ? entry_salt : fallback_salt
    bucket_hit(effective_pct(entry, now), pick_identifier(user, bucket_by), salt)
  end
end

.match_rule(rule, user) ⇒ Object



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
# File 'lib/shipeasy/sdk/eval.rb', line 23

def self.match_rule(rule, user)
  attr  = rule["attr"] || rule[:attr]
  op    = rule["op"]   || rule[:op]
  value = rule["value"] || rule[:value]
  actual = user[attr] || user[attr.to_sym]

  case op
  when "eq"       then actual == value
  when "neq"      then actual != value
  when "in"       then Array(value).include?(actual)
  when "not_in"   then !Array(value).include?(actual)
  when "contains"
    if actual.is_a?(String) && value.is_a?(String)
      actual.include?(value)
    elsif actual.is_a?(Array)
      actual.include?(value)
    else
      false
    end
  when "regex"
    actual.is_a?(String) && value.is_a?(String) &&
      Regexp.new(value).match?(actual) rescue false
  when "gt", "gte", "lt", "lte"
    a = to_num(actual)
    b = to_num(value)
    return false if a.nil? || b.nil?
    case op
    when "gt"  then a > b
    when "gte" then a >= b
    when "lt"  then a < b
    when "lte" then a <= b
    end
  else
    false
  end
end

.merge_params(param_defaults, group_params) ⇒ Object

universeDefaults ⊕ variantOverride — a variant inherits every universe default it doesn't explicitly override. A nil defaults map short-circuits to the variant params (dup'd) alone.



202
203
204
205
# File 'lib/shipeasy/sdk/eval.rb', line 202

def self.merge_params(param_defaults, group_params)
  gp = group_params || {}
  param_defaults ? param_defaults.merge(gp) : gp.dup
end

.murmur3(key) ⇒ Object



6
7
8
# File 'lib/shipeasy/sdk/eval.rb', line 6

def self.murmur3(key)
  Murmur3.hash32(key, 0)
end

.param_defaults_from_schema(schema) ⇒ Object

Flatten a universe param schema ([{ "name", "type", "default" }, ...]) to a plain name => default map — the defaults assign() layers under a variant's override map. Returns nil for a null/empty schema so the merge short-circuits. Mirrors the TS reference / @shipeasy/core.



191
192
193
194
195
196
197
# File 'lib/shipeasy/sdk/eval.rb', line 191

def self.param_defaults_from_schema(schema)
  return nil if schema.nil? || schema.empty?
  schema.each_with_object({}) do |p, h|
    name = p["name"] || p[:name]
    h[name] = p.key?("default") ? p["default"] : p[:default]
  end
end

.pick_identifier(user, bucket_by) ⇒ Object

Pick the bucketing identifier. When bucket_by is set and the user carries that attribute as a non-empty string (or any number, stringified), bucket on it — so a whole company/org lands on one variant. Otherwise fall back to user_id, then anonymous_id. Mirrors core's pickIdentifier.



64
65
66
67
68
69
70
71
# File 'lib/shipeasy/sdk/eval.rb', line 64

def self.pick_identifier(user, bucket_by)
  if bucket_by && !bucket_by.to_s.empty?
    v = user[bucket_by] || user[bucket_by.to_sym]
    return v if v.is_a?(String) && !v.empty?
    return v.to_s if v.is_a?(Numeric)
  end
  user["user_id"] || user[:user_id] || user["anonymous_id"] || user[:anonymous_id]
end

.resolve_forced_group(exp, uid, flags_blob, user) ⇒ Object

exp_name + sticky_store are optional so existing callers stay deterministic. When a sticky_store is passed, an enrolled unit whose stored salt prefix still matches skips the allocation gate (so a shrinking allocation keeps it in) and returns the stored group without re-running the pick. A fresh pick is persisted via store.set; a salt mismatch / missing stored group falls through to re-bucket + overwrite. Mirrors the TS reference (doc 20 §2). exp_name is the key under which the entry is stored.

Pooling / holdout-gate / reserved-headroom / universe param-default merge (doc 20 §B) are layered in here so both the low-level parity path and the universe assign() path share ONE classify. The added steps are all guarded by presence checks, so a legacy blob (no hashVersion/pool/reserved) behaves exactly as before. Resolve a forced override group for uid (spec step 1): ID overrides (tier 1) beat cohort/GK overrides (tier 2); within cohort overrides the first (pre-sorted by priority) gate that passes wins. Returns the forced group name or nil. The caller applies eligibility + group-existence (forced-but-gated). Mirrors @shipeasy/core resolveForcedGroup.



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/shipeasy/sdk/eval.rb', line 225

def self.resolve_forced_group(exp, uid, flags_blob, user)
  id_overrides = exp["idOverrides"] || exp[:idOverrides]
  if id_overrides
    by_id = id_overrides[uid]
    return by_id if by_id && !by_id.to_s.empty?
  end
  cohort_overrides = exp["cohortOverrides"] || exp[:cohortOverrides]
  if cohort_overrides
    cohort_overrides.each do |co|
      gname = co["gate"] || co[:gate]
      gate = flags_blob&.dig("gates", gname)
      return (co["group"] || co[:group]) if gate && eval_gate(gate, user)
    end
  end
  nil
end

.to_num(v) ⇒ Object



14
15
16
17
18
19
20
21
# File 'lib/shipeasy/sdk/eval.rb', line 14

def self.to_num(v)
  case v
  when Numeric then v.finite? ? v : nil
  when String
    n = Float(v) rescue nil
    n&.finite? ? n : nil
  end
end