@vllnt/convex-experiments 0.2.0-canary.38e0a3a → 0.2.0-canary.6def607

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@ import { api } from "./_generated/api.js";
3
3
  import type { Doc } from "./_generated/dataModel.js";
4
4
  import type { MutationCtx } from "./_generated/server.js";
5
5
  import { mutation } from "./_generated/server.js";
6
- import { pickVariant, type Variant } from "../shared.js";
6
+ import { MAX_ID_LENGTH, MAX_VARIANTS, pickVariant, type Variant } from "../shared.js";
7
7
  import { assignResult, experimentStatus, exposureResult, variant } from "./validators.js";
8
8
 
9
9
  /** Reject empty identifiers: an empty scope/key/subjectRef would store a meaningless row. */
@@ -18,6 +18,43 @@ function assertNonEmpty(fields: Record<string, string>): void {
18
18
  }
19
19
  }
20
20
 
21
+ /**
22
+ * Reject an identifier longer than `MAX_ID_LENGTH` UTF-16 code units (JavaScript
23
+ * `string.length`). Called only where new data is written, never on a path that
24
+ * reads, updates the status of, erases or deletes rows that already exist.
25
+ */
26
+ function assertMaxLength(fields: Record<string, string>): void {
27
+ for (const [name, value] of Object.entries(fields)) {
28
+ if (value.length > MAX_ID_LENGTH) {
29
+ throw new ConvexError({
30
+ code: "INVALID_ARGUMENT",
31
+ message: `${name} must be at most ${MAX_ID_LENGTH} UTF-16 code units`,
32
+ });
33
+ }
34
+ }
35
+ }
36
+
37
+ /** Reject a variant set over `MAX_VARIANTS`, or with a variant key over `MAX_ID_LENGTH`, and a salt over it. */
38
+ function assertDefinitionSize(variants: readonly Variant[], salt: string): void {
39
+ assertMaxLength({ salt });
40
+ if (variants.length > MAX_VARIANTS) {
41
+ throw new ConvexError({
42
+ code: "INVALID_VARIANTS",
43
+ reason: "too_many",
44
+ message: `an experiment has at most ${MAX_VARIANTS} variants`,
45
+ });
46
+ }
47
+ for (const candidate of variants) {
48
+ if (candidate.key.length > MAX_ID_LENGTH) {
49
+ throw new ConvexError({
50
+ code: "INVALID_VARIANTS",
51
+ reason: "key_too_long",
52
+ message: `variant keys must be at most ${MAX_ID_LENGTH} UTF-16 code units`,
53
+ });
54
+ }
55
+ }
56
+ }
57
+
21
58
  /**
22
59
  * Reject a malformed variant set before any write: at least one variant, every
23
60
  * weight a positive finite number, and no duplicate variant keys. The thrown
@@ -130,6 +167,7 @@ async function ensureAssignment(
130
167
  if (existing !== null) {
131
168
  return { variant: existing.variant, isNew: false };
132
169
  }
170
+ assertMaxLength({ subjectRef });
133
171
  const variantKey = pickVariant(experiment.variants, hashSalt(experiment), subjectRef);
134
172
  await ctx.db.insert("assignments", {
135
173
  scope: experiment.scope,
@@ -157,8 +195,15 @@ function variantsChanged(a: readonly Variant[], b: readonly Variant[]): boolean
157
195
  * tallies. Status transitions (start/stop) are always allowed. To re-randomize or
158
196
  * reweight after enrollment, define a new experiment key.
159
197
  *
160
- * @throws `ConvexError({ code: "INVALID_ARGUMENT" })` when `scope` or `key` is empty.
161
- * @throws `ConvexError({ code: "INVALID_VARIANTS", reason })` for a bad variant set.
198
+ * **Size limits (new data only):** a new experiment needs `scope`, `key` and `salt`
199
+ * of at most 512 UTF-16 code units; a new or changed variant set needs at most 100
200
+ * variants whose keys are each at most 512. An update that changes neither
201
+ * `variants` nor `salt` is never rejected for the length of existing values.
202
+ *
203
+ * @throws `ConvexError({ code: "INVALID_ARGUMENT" })` when `scope` or `key` is empty,
204
+ * or when `scope`, `key` or `salt` is over 512 UTF-16 code units (new data only).
205
+ * @throws `ConvexError({ code: "INVALID_VARIANTS", reason })` for a bad variant set;
206
+ * `reason` is `too_many` (over 100) or `key_too_long` (a key over 512) for the caps.
162
207
  * @throws `ConvexError({ code: "EXPERIMENT_LOCKED" })` when `variants`/`salt` change
163
208
  * after a subject has been assigned.
164
209
  */
@@ -181,6 +226,8 @@ export const define = mutation({
181
226
  )
182
227
  .unique();
183
228
  if (existing === null) {
229
+ assertMaxLength({ scope: args.scope, key: args.key });
230
+ assertDefinitionSize(args.variants, args.salt);
184
231
  await ctx.db.insert("experiments", {
185
232
  key: args.key,
186
233
  scope: args.scope,
@@ -194,6 +241,7 @@ export const define = mutation({
194
241
  const definitionChanged =
195
242
  variantsChanged(existing.variants, args.variants) || existing.salt !== args.salt;
196
243
  if (definitionChanged) {
244
+ assertDefinitionSize(args.variants, args.salt);
197
245
  const firstAssignment = await ctx.db
198
246
  .query("assignments")
199
247
  .withIndex("by_scope_experiment_subject", (q) =>
@@ -225,7 +273,8 @@ export const define = mutation({
225
273
  * Move an experiment to a new lifecycle `status`. Returns `false` when no
226
274
  * experiment exists for `(scope, key)`, `true` when it exists. Stopping an
227
275
  * experiment freezes enrollment (`assign` returns `{ variant: null }`) while
228
- * leaving recorded assignments and exposures intact.
276
+ * leaving recorded assignments and exposures intact. Applies no length limit, so
277
+ * an experiment stored with a longer `scope` or `key` can still change status.
229
278
  */
230
279
  export const setStatus = mutation({
231
280
  args: { scope: v.string(), key: v.string(), status: experimentStatus },
@@ -253,6 +302,10 @@ export const setStatus = mutation({
253
302
  * experiment is absent or not `running` (the host treats it as control). When
254
303
  * `running`, the first call deterministically picks and persists a variant
255
304
  * (`isNew: true`); later calls replay it (`isNew: false`). Time is server-sourced.
305
+ *
306
+ * @throws `ConvexError({ code: "INVALID_ARGUMENT" })` when an argument is empty, or
307
+ * when a new assignment's `subjectRef` is over 512 UTF-16 code units. A stored
308
+ * assignment with a longer `subjectRef` is still replayed.
256
309
  */
257
310
  export const assign = mutation({
258
311
  args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
@@ -284,6 +337,10 @@ export const assign = mutation({
284
337
  * or `logExposure` created it. Later exposures bump the row's `count` and the
285
338
  * tally's `exposures` only (deduped per subject). `{ variant: null }`
286
339
  * when the experiment is absent or not `running`. Time is server-sourced.
340
+ *
341
+ * @throws `ConvexError({ code: "INVALID_ARGUMENT" })` when an argument is empty, or
342
+ * when enrolling a new subject whose `subjectRef` is over 512 UTF-16 code units.
343
+ * A subject already stored with a longer `subjectRef` can still log exposures.
287
344
  */
288
345
  export const logExposure = mutation({
289
346
  args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
@@ -349,6 +406,7 @@ export const logExposure = mutation({
349
406
  * rows — decrementing the variant tallies accordingly. The GDPR right-to-erasure
350
407
  * primitive for a `subjectRef` that maps to a person. Returns `true` if anything
351
408
  * was deleted. Loop over `listExperiments` to erase a subject across a scope.
409
+ * Applies no length limit, so rows stored with a longer `subjectRef` can be erased.
352
410
  */
353
411
  export const forgetSubject = mutation({
354
412
  args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
@@ -398,7 +456,8 @@ export const forgetSubject = mutation({
398
456
  * exposure, and tally row. Bounded: removes up to `batch` rows per table per pass
399
457
  * and self-reschedules until the children are drained, then deletes the definition.
400
458
  * Idempotent and safe to call on an absent experiment. Returns the rows removed
401
- * this pass.
459
+ * this pass. Applies no length limit, so an experiment stored with a longer `scope`
460
+ * or `key` can be deleted.
402
461
  */
403
462
  export const deleteExperiment = mutation({
404
463
  args: { scope: v.string(), key: v.string(), batch: v.number() },
@@ -34,7 +34,10 @@ export const getExperiment = query({
34
34
  },
35
35
  });
36
36
 
37
- /** Every experiment in a scope, optionally filtered by `status`. */
37
+ /**
38
+ * Every experiment in a scope, optionally filtered by `status`, in creation order
39
+ * (the `by_scope` index breaks ties on `_creationTime`).
40
+ */
38
41
  export const listExperiments = query({
39
42
  args: { scope: v.string(), status: v.optional(experimentStatus) },
40
43
  returns: v.array(experimentDef),
package/src/shared.ts CHANGED
@@ -11,6 +11,16 @@ export const DEFAULT_STATUS = "running";
11
11
  /** Default page size for a `deleteExperiment` cascade pass before it self-reschedules. */
12
12
  export const DEFAULT_DELETE_BATCH = 200;
13
13
 
14
+ /**
15
+ * Longest identifier a mutation accepts for new data: `scope`, `key`, `salt`,
16
+ * `subjectRef` and each variant key. Counted as JavaScript `string.length`, that
17
+ * is UTF-16 code units (an emoji counts as 2), not characters and not UTF-8 bytes.
18
+ */
19
+ export const MAX_ID_LENGTH = 512;
20
+
21
+ /** Most variants an experiment definition accepts when it is created or changed. */
22
+ export const MAX_VARIANTS = 100;
23
+
14
24
  /** A weighted variant: an opaque variant key and its relative selection weight. */
15
25
  export interface Variant {
16
26
  /** The host's opaque variant key (e.g. `"control"`, `"treatment"`). */
@@ -34,13 +44,31 @@ export function fnv1a(input: string): number {
34
44
  return hash >>> 0;
35
45
  }
36
46
 
47
+ /**
48
+ * The murmur3 32-bit finalizer (`fmix32`): spreads every input bit across the
49
+ * whole output. FNV-1a alone leaves inputs that differ only in their last
50
+ * characters (`u1`, `u2`, …) close together, which skews a weighted split.
51
+ */
52
+ function fmix32(input: number): number {
53
+ let hash = input;
54
+ hash ^= hash >>> 16;
55
+ hash = Math.imul(hash, 0x85ebca6b);
56
+ hash ^= hash >>> 13;
57
+ hash = Math.imul(hash, 0xc2b2ae35);
58
+ hash ^= hash >>> 16;
59
+ return hash >>> 0;
60
+ }
61
+
37
62
  /**
38
63
  * Deterministically pick a variant for `subjectRef` from `variants`, weighted by
39
- * each variant's `weight`. The same `(salt, subjectRef)` always maps to the same
40
- * variant — sticky assignment with no storage — and the distribution matches the
41
- * weights. The component folds `scope` into the salt so the same subject buckets
42
- * independently per scope. Assumes a non-empty `variants` with positive weights;
43
- * the caller validates that upstream.
64
+ * each variant's `weight`. The bucket is FNV-1a over the UTF-16 code units of
65
+ * `"<salt>:<subjectRef>"`, then the murmur3 `fmix32` finalizer, mapped onto the
66
+ * cumulative-weight line in definition order. The same `(salt, subjectRef)`
67
+ * always maps to the same variant — sticky assignment with no storage — and each
68
+ * variant's share is `weight / sum(weights)`, also for similar or sequential
69
+ * `subjectRef`s. The component folds `scope` into the salt so the same subject
70
+ * buckets independently per scope. Assumes a non-empty `variants` with positive
71
+ * weights; the caller validates that upstream.
44
72
  */
45
73
  export function pickVariant(
46
74
  variants: readonly Variant[],
@@ -56,7 +84,7 @@ export function pickVariant(
56
84
  total += variant.weight;
57
85
  }
58
86
  // Map the hash into [0, total): a point on the cumulative-weight line.
59
- let target = (fnv1a(`${salt}:${subjectRef}`) / 0x100000000) * total;
87
+ let target = (fmix32(fnv1a(`${salt}:${subjectRef}`)) / 0x100000000) * total;
60
88
  // Walk every variant but the last, subtracting its bucket width.
61
89
  for (const variant of variants.slice(0, -1)) {
62
90
  target -= variant.weight;