@vllnt/convex-experiments 0.1.0-canary.f2cd1ba → 0.1.1-canary.b4e25b0

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.
Files changed (51) hide show
  1. package/README.md +150 -36
  2. package/dist/client/index.d.ts +54 -3
  3. package/dist/client/index.d.ts.map +1 -1
  4. package/dist/client/index.js +53 -4
  5. package/dist/client/index.js.map +1 -1
  6. package/dist/client/types.d.ts +8 -3
  7. package/dist/client/types.d.ts.map +1 -1
  8. package/dist/component/_generated/component.d.ts +35 -0
  9. package/dist/component/_generated/component.d.ts.map +1 -1
  10. package/dist/component/_generated/server.d.ts +12 -0
  11. package/dist/component/_generated/server.d.ts.map +1 -1
  12. package/dist/component/_generated/server.js +2 -0
  13. package/dist/component/_generated/server.js.map +1 -1
  14. package/dist/component/convex.config.d.ts.map +1 -1
  15. package/dist/component/mutations.d.ts +47 -20
  16. package/dist/component/mutations.d.ts.map +1 -1
  17. package/dist/component/mutations.js +220 -26
  18. package/dist/component/mutations.js.map +1 -1
  19. package/dist/component/queries.d.ts +41 -8
  20. package/dist/component/queries.d.ts.map +1 -1
  21. package/dist/component/queries.js +82 -20
  22. package/dist/component/queries.js.map +1 -1
  23. package/dist/component/schema.d.ts +39 -17
  24. package/dist/component/schema.d.ts.map +1 -1
  25. package/dist/component/schema.js +20 -5
  26. package/dist/component/schema.js.map +1 -1
  27. package/dist/component/validators.d.ts +31 -18
  28. package/dist/component/validators.d.ts.map +1 -1
  29. package/dist/component/validators.js +14 -3
  30. package/dist/component/validators.js.map +1 -1
  31. package/dist/react/index.d.ts +57 -0
  32. package/dist/react/index.d.ts.map +1 -0
  33. package/dist/react/index.js +39 -0
  34. package/dist/react/index.js.map +1 -0
  35. package/dist/shared.d.ts +5 -3
  36. package/dist/shared.d.ts.map +1 -1
  37. package/dist/shared.js +5 -3
  38. package/dist/shared.js.map +1 -1
  39. package/package.json +50 -20
  40. package/src/client/index.ts +98 -4
  41. package/src/client/types.ts +8 -3
  42. package/src/component/_generated/component.ts +42 -1
  43. package/src/component/_generated/server.ts +13 -0
  44. package/src/component/mutations.ts +250 -28
  45. package/src/component/queries.ts +97 -20
  46. package/src/component/schema.ts +21 -5
  47. package/src/component/validators.ts +14 -3
  48. package/src/react/index.tsx +68 -0
  49. package/src/shared.ts +6 -3
  50. package/src/test.ts +2 -1
  51. package/src/unit.test.ts +0 -84
@@ -1,36 +1,60 @@
1
1
  import { ConvexError, v } from "convex/values";
2
- import type { Doc } from "./_generated/dataModel";
3
- import type { MutationCtx } from "./_generated/server";
4
- import { mutation } from "./_generated/server";
5
- import { pickVariant, type Variant } from "../shared";
6
- import { assignResult, experimentStatus, exposureResult, variant } from "./validators";
2
+ import { api } from "./_generated/api.js";
3
+ import type { Doc } from "./_generated/dataModel.js";
4
+ import type { MutationCtx } from "./_generated/server.js";
5
+ import { mutation } from "./_generated/server.js";
6
+ import { pickVariant, type Variant } from "../shared.js";
7
+ import { assignResult, experimentStatus, exposureResult, variant } from "./validators.js";
8
+
9
+ /** Reject empty identifiers: an empty scope/key/subjectRef would store a meaningless row. */
10
+ function assertNonEmpty(fields: Record<string, string>): void {
11
+ for (const [name, value] of Object.entries(fields)) {
12
+ if (value === "") {
13
+ throw new ConvexError({
14
+ code: "INVALID_ARGUMENT",
15
+ message: `${name} must be non-empty`,
16
+ });
17
+ }
18
+ }
19
+ }
7
20
 
8
21
  /**
9
22
  * Reject a malformed variant set before any write: at least one variant, every
10
- * weight a positive finite number, and no duplicate variant keys. A zero/negative
11
- * weight would distort or zero out a bucket; a duplicate key would make
12
- * assignment ambiguous.
23
+ * weight a positive finite number, and no duplicate variant keys. The thrown
24
+ * `ConvexError` carries a `reason` so the host can branch on the specific failure.
13
25
  *
14
- * @throws `ConvexError({ code: "INVALID_VARIANTS" })`
26
+ * @throws `ConvexError({ code: "INVALID_VARIANTS", reason })`
15
27
  */
16
28
  function validateVariants(variants: readonly Variant[]): void {
17
29
  if (variants.length === 0) {
18
30
  throw new ConvexError({
19
31
  code: "INVALID_VARIANTS",
32
+ reason: "empty",
20
33
  message: "an experiment needs at least one variant",
21
34
  });
22
35
  }
23
36
  const seen = new Set<string>();
24
37
  for (const candidate of variants) {
38
+ if (candidate.key === "") {
39
+ throw new ConvexError({
40
+ code: "INVALID_VARIANTS",
41
+ reason: "empty_key",
42
+ message: "variant keys must be non-empty",
43
+ });
44
+ }
25
45
  if (!(candidate.weight > 0 && isFinite(candidate.weight))) {
26
46
  throw new ConvexError({
27
47
  code: "INVALID_VARIANTS",
48
+ reason: "non_positive_weight",
49
+ key: candidate.key,
28
50
  message: `variant "${candidate.key}" weight must be a positive finite number`,
29
51
  });
30
52
  }
31
53
  if (seen.has(candidate.key)) {
32
54
  throw new ConvexError({
33
55
  code: "INVALID_VARIANTS",
56
+ reason: "duplicate_key",
57
+ key: candidate.key,
34
58
  message: `duplicate variant key "${candidate.key}"`,
35
59
  });
36
60
  }
@@ -38,10 +62,55 @@ function validateVariants(variants: readonly Variant[]): void {
38
62
  }
39
63
  }
40
64
 
65
+ /**
66
+ * The hash salt for an experiment folds in `scope` so the same `subjectRef` lands
67
+ * in an independent bucket per scope (a tenant-correlation bug otherwise) and the
68
+ * host's `salt` re-keys within the scope.
69
+ */
70
+ function hashSalt(experiment: Doc<"experiments">): string {
71
+ return `${experiment.scope}:${experiment.salt}`;
72
+ }
73
+
74
+ /** Incrementally maintain the per-`(scope, experiment, variant)` tally row. */
75
+ async function bumpTally(
76
+ ctx: MutationCtx,
77
+ scope: string,
78
+ experimentKey: string,
79
+ variantKey: string,
80
+ delta: { assigned?: number; subjects?: number; exposures?: number },
81
+ ): Promise<void> {
82
+ const assigned = delta.assigned ?? 0;
83
+ const subjects = delta.subjects ?? 0;
84
+ const exposures = delta.exposures ?? 0;
85
+ const row = await ctx.db
86
+ .query("variantTallies")
87
+ .withIndex("by_scope_experiment_variant", (q) =>
88
+ q.eq("scope", scope).eq("experimentKey", experimentKey).eq("variant", variantKey),
89
+ )
90
+ .unique();
91
+ if (row === null) {
92
+ await ctx.db.insert("variantTallies", {
93
+ scope,
94
+ experimentKey,
95
+ variant: variantKey,
96
+ assigned,
97
+ subjects,
98
+ exposures,
99
+ });
100
+ } else {
101
+ await ctx.db.patch("variantTallies", row._id, {
102
+ assigned: row.assigned + assigned,
103
+ subjects: row.subjects + subjects,
104
+ exposures: row.exposures + exposures,
105
+ });
106
+ }
107
+ }
108
+
41
109
  /**
42
110
  * Return the subject's sticky assignment, persisting a fresh deterministic pick on
43
- * first sight. Plain helper (not a Convex function) so `assign` and `logExposure`
44
- * share one enrollment path. Time is server-sourced by the caller.
111
+ * first sight (and bumping the variant's `assigned` tally). Plain helper (not a
112
+ * Convex function) so `assign` and `logExposure` share one enrollment path. Time is
113
+ * server-sourced by the caller.
45
114
  */
46
115
  async function ensureAssignment(
47
116
  ctx: MutationCtx,
@@ -61,7 +130,7 @@ async function ensureAssignment(
61
130
  if (existing !== null) {
62
131
  return { variant: existing.variant, isNew: false };
63
132
  }
64
- const variantKey = pickVariant(experiment.variants, experiment.salt, subjectRef);
133
+ const variantKey = pickVariant(experiment.variants, hashSalt(experiment), subjectRef);
65
134
  await ctx.db.insert("assignments", {
66
135
  scope: experiment.scope,
67
136
  experimentKey: experiment.key,
@@ -69,17 +138,30 @@ async function ensureAssignment(
69
138
  variant: variantKey,
70
139
  assignedAt: now,
71
140
  });
141
+ await bumpTally(ctx, experiment.scope, experiment.key, variantKey, { assigned: 1 });
72
142
  return { variant: variantKey, isNew: true };
73
143
  }
74
144
 
145
+ /** True when two variant sets differ in key, weight, or order. */
146
+ function variantsChanged(a: readonly Variant[], b: readonly Variant[]): boolean {
147
+ return JSON.stringify(a) !== JSON.stringify(b);
148
+ }
149
+
75
150
  /**
76
151
  * Create or update an experiment definition, keyed by `(scope, key)`. Returns
77
- * `{ created: true }` on insert, `{ created: false }` on update. Updating leaves
78
- * existing sticky assignments untouched — only the definition (variants, salt,
79
- * status) changes. Time is server-sourced.
152
+ * `{ created: true }` on insert, `{ created: false }` on update. Time is
153
+ * server-sourced.
80
154
  *
81
- * @throws `ConvexError({ code: "INVALID_VARIANTS" })` when the variant set is
82
- * empty, has a non-positive/non-finite weight, or repeats a variant key.
155
+ * **Immutability once assigned:** `variants` and `salt` are fixed once any subject
156
+ * is assigned — changing them would split the population across two randomizations
157
+ * (some subjects bucketed under the old definition, some the new) and orphan
158
+ * tallies. Status transitions (start/stop) are always allowed. To re-randomize or
159
+ * reweight after enrollment, define a new experiment key.
160
+ *
161
+ * @throws `ConvexError({ code: "INVALID_ARGUMENT" })` when `scope` or `key` is empty.
162
+ * @throws `ConvexError({ code: "INVALID_VARIANTS", reason })` for a bad variant set.
163
+ * @throws `ConvexError({ code: "EXPERIMENT_LOCKED" })` when `variants`/`salt` change
164
+ * after a subject has been assigned.
83
165
  */
84
166
  export const define = mutation({
85
167
  args: {
@@ -91,6 +173,7 @@ export const define = mutation({
91
173
  },
92
174
  returns: v.object({ created: v.boolean() }),
93
175
  handler: async (ctx, args) => {
176
+ assertNonEmpty({ scope: args.scope, key: args.key });
94
177
  validateVariants(args.variants);
95
178
  const existing = await ctx.db
96
179
  .query("experiments")
@@ -109,7 +192,22 @@ export const define = mutation({
109
192
  });
110
193
  return { created: true };
111
194
  }
112
- await ctx.db.patch(existing._id, {
195
+ if (variantsChanged(existing.variants, args.variants) || existing.salt !== args.salt) {
196
+ const firstAssignment = await ctx.db
197
+ .query("assignments")
198
+ .withIndex("by_scope_experiment_subject", (q) =>
199
+ q.eq("scope", args.scope).eq("experimentKey", args.key),
200
+ )
201
+ .first();
202
+ if (firstAssignment !== null) {
203
+ throw new ConvexError({
204
+ code: "EXPERIMENT_LOCKED",
205
+ message:
206
+ "variants and salt are immutable once subjects are assigned; define a new experiment key to re-randomize",
207
+ });
208
+ }
209
+ }
210
+ await ctx.db.patch("experiments", existing._id, {
113
211
  status: args.status,
114
212
  variants: args.variants,
115
213
  salt: args.salt,
@@ -128,6 +226,7 @@ export const setStatus = mutation({
128
226
  args: { scope: v.string(), key: v.string(), status: experimentStatus },
129
227
  returns: v.boolean(),
130
228
  handler: async (ctx, args) => {
229
+ assertNonEmpty({ scope: args.scope, key: args.key });
131
230
  const existing = await ctx.db
132
231
  .query("experiments")
133
232
  .withIndex("by_scope_key", (q) =>
@@ -137,7 +236,7 @@ export const setStatus = mutation({
137
236
  if (existing === null) {
138
237
  return false;
139
238
  }
140
- await ctx.db.patch(existing._id, { status: args.status });
239
+ await ctx.db.patch("experiments", existing._id, { status: args.status });
141
240
  return true;
142
241
  },
143
242
  });
@@ -146,14 +245,13 @@ export const setStatus = mutation({
146
245
  * Enroll `subjectRef` and return the sticky variant. `{ variant: null }` when the
147
246
  * experiment is absent or not `running` (the host treats it as control). When
148
247
  * `running`, the first call deterministically picks and persists a variant
149
- * (`isNew: true`); later calls replay it (`isNew: false`). Assignment is a pure
150
- * function of `(salt, subjectRef)` — see {@link pickVariant} — so it is sticky
151
- * even before persistence. Time is server-sourced.
248
+ * (`isNew: true`); later calls replay it (`isNew: false`). Time is server-sourced.
152
249
  */
153
250
  export const assign = mutation({
154
251
  args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
155
252
  returns: assignResult,
156
253
  handler: async (ctx, args) => {
254
+ assertNonEmpty({ scope: args.scope, key: args.key, subjectRef: args.subjectRef });
157
255
  const experiment = await ctx.db
158
256
  .query("experiments")
159
257
  .withIndex("by_scope_key", (q) =>
@@ -168,16 +266,16 @@ export const assign = mutation({
168
266
  });
169
267
 
170
268
  /**
171
- * Record that `subjectRef` was exposed to the experiment and return their variant.
172
- * Enrolls the subject if needed (same sticky path as `assign`), then upserts a
173
- * per-subject exposure row — first exposure inserts (`count` 1), later exposures
174
- * bump `count` and `lastExposedAt`. The deduped tally is what `results` reports as
175
- * unique subjects. `{ variant: null }` when not enrolled. Time is server-sourced.
269
+ * Record that `subjectRef` was exposed and return their variant, enrolling if
270
+ * needed. First exposure inserts a tally row and bumps `subjects` + `exposures`;
271
+ * later exposures bump `exposures` only (deduped per subject). `{ variant: null }`
272
+ * when not enrolled. Time is server-sourced.
176
273
  */
177
274
  export const logExposure = mutation({
178
275
  args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
179
276
  returns: exposureResult,
180
277
  handler: async (ctx, args) => {
278
+ assertNonEmpty({ scope: args.scope, key: args.key, subjectRef: args.subjectRef });
181
279
  const experiment = await ctx.db
182
280
  .query("experiments")
183
281
  .withIndex("by_scope_key", (q) =>
@@ -213,12 +311,136 @@ export const logExposure = mutation({
213
311
  lastExposedAt: now,
214
312
  count: 1,
215
313
  });
314
+ await bumpTally(ctx, args.scope, args.key, variantKey, {
315
+ subjects: 1,
316
+ exposures: 1,
317
+ });
216
318
  } else {
217
- await ctx.db.patch(existing._id, {
319
+ await ctx.db.patch("exposures", existing._id, {
218
320
  lastExposedAt: now,
219
321
  count: existing.count + 1,
220
322
  });
323
+ await bumpTally(ctx, args.scope, args.key, variantKey, { exposures: 1 });
221
324
  }
222
325
  return { variant: variantKey };
223
326
  },
224
327
  });
328
+
329
+ /**
330
+ * Erase a subject's footprint in one experiment — their assignment and exposure
331
+ * rows — decrementing the variant tallies accordingly. The GDPR right-to-erasure
332
+ * primitive for a `subjectRef` that maps to a person. Returns `true` if anything
333
+ * was deleted. Loop over `listExperiments` to erase a subject across a scope.
334
+ */
335
+ export const forgetSubject = mutation({
336
+ args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
337
+ returns: v.boolean(),
338
+ handler: async (ctx, args) => {
339
+ assertNonEmpty({ scope: args.scope, key: args.key, subjectRef: args.subjectRef });
340
+ let deleted = false;
341
+ const assignment = await ctx.db
342
+ .query("assignments")
343
+ .withIndex("by_scope_experiment_subject", (q) =>
344
+ q
345
+ .eq("scope", args.scope)
346
+ .eq("experimentKey", args.key)
347
+ .eq("subjectRef", args.subjectRef),
348
+ )
349
+ .unique();
350
+ if (assignment !== null) {
351
+ await bumpTally(ctx, args.scope, args.key, assignment.variant, {
352
+ assigned: -1,
353
+ });
354
+ await ctx.db.delete("assignments", assignment._id);
355
+ deleted = true;
356
+ }
357
+ const exposure = await ctx.db
358
+ .query("exposures")
359
+ .withIndex("by_scope_experiment_subject", (q) =>
360
+ q
361
+ .eq("scope", args.scope)
362
+ .eq("experimentKey", args.key)
363
+ .eq("subjectRef", args.subjectRef),
364
+ )
365
+ .unique();
366
+ if (exposure !== null) {
367
+ await bumpTally(ctx, args.scope, args.key, exposure.variant, {
368
+ subjects: -1,
369
+ exposures: -exposure.count,
370
+ });
371
+ await ctx.db.delete("exposures", exposure._id);
372
+ deleted = true;
373
+ }
374
+ return deleted;
375
+ },
376
+ });
377
+
378
+ /**
379
+ * Delete an experiment and all of its data — the definition, every assignment,
380
+ * exposure, and tally row. Bounded: removes up to `batch` rows per table per pass
381
+ * and self-reschedules until the children are drained, then deletes the definition.
382
+ * Idempotent and safe to call on an absent experiment. Returns the rows removed
383
+ * this pass.
384
+ */
385
+ export const deleteExperiment = mutation({
386
+ args: { scope: v.string(), key: v.string(), batch: v.number() },
387
+ returns: v.number(),
388
+ handler: async (ctx, args) => {
389
+ assertNonEmpty({ scope: args.scope, key: args.key });
390
+ if (!Number.isFinite(args.batch) || !Number.isInteger(args.batch) || args.batch < 1 || args.batch > 500) {
391
+ throw new ConvexError({
392
+ code: "INVALID_BATCH",
393
+ message: "batch must be an integer between 1 and 500",
394
+ });
395
+ }
396
+ let removed = 0;
397
+ const assignments = await ctx.db
398
+ .query("assignments")
399
+ .withIndex("by_scope_experiment_subject", (q) =>
400
+ q.eq("scope", args.scope).eq("experimentKey", args.key),
401
+ )
402
+ .take(args.batch);
403
+ for (const row of assignments) {
404
+ await ctx.db.delete("assignments", row._id);
405
+ removed++;
406
+ }
407
+ const exposures = await ctx.db
408
+ .query("exposures")
409
+ .withIndex("by_scope_experiment", (q) =>
410
+ q.eq("scope", args.scope).eq("experimentKey", args.key),
411
+ )
412
+ .take(args.batch);
413
+ for (const row of exposures) {
414
+ await ctx.db.delete("exposures", row._id);
415
+ removed++;
416
+ }
417
+ const tallies = await ctx.db
418
+ .query("variantTallies")
419
+ .withIndex("by_scope_experiment", (q) =>
420
+ q.eq("scope", args.scope).eq("experimentKey", args.key),
421
+ )
422
+ .take(args.batch);
423
+ for (const row of tallies) {
424
+ await ctx.db.delete("variantTallies", row._id);
425
+ removed++;
426
+ }
427
+ if (removed > 0) {
428
+ await ctx.scheduler.runAfter(0, api.mutations.deleteExperiment, {
429
+ scope: args.scope,
430
+ key: args.key,
431
+ batch: args.batch,
432
+ });
433
+ return removed;
434
+ }
435
+ const def = await ctx.db
436
+ .query("experiments")
437
+ .withIndex("by_scope_key", (q) =>
438
+ q.eq("scope", args.scope).eq("key", args.key),
439
+ )
440
+ .unique();
441
+ if (def !== null) {
442
+ await ctx.db.delete("experiments", def._id);
443
+ }
444
+ return removed;
445
+ },
446
+ });
@@ -1,10 +1,13 @@
1
1
  import { v } from "convex/values";
2
- import { query } from "./_generated/server";
2
+ import { query } from "./_generated/server.js";
3
+ import { pickVariant } from "../shared.js";
3
4
  import {
4
5
  assignmentProjection,
5
6
  experimentDef,
7
+ experimentStatus,
8
+ exposureResult,
6
9
  variantResult,
7
- } from "./validators";
10
+ } from "./validators.js";
8
11
 
9
12
  /** The experiment definition for `(scope, key)`, or `null` if none exists. */
10
13
  export const getExperiment = query({
@@ -31,6 +34,30 @@ export const getExperiment = query({
31
34
  },
32
35
  });
33
36
 
37
+ /** Every experiment in a scope, optionally filtered by `status`. */
38
+ export const listExperiments = query({
39
+ args: { scope: v.string(), status: v.optional(experimentStatus) },
40
+ returns: v.array(experimentDef),
41
+ handler: async (ctx, args) => {
42
+ const rows = await ctx.db
43
+ .query("experiments")
44
+ .withIndex("by_scope", (q) => q.eq("scope", args.scope))
45
+ .collect();
46
+ const filtered =
47
+ args.status === undefined
48
+ ? rows
49
+ : rows.filter((row) => row.status === args.status);
50
+ return filtered.map((row) => ({
51
+ key: row.key,
52
+ scope: row.scope,
53
+ status: row.status,
54
+ variants: row.variants,
55
+ salt: row.salt,
56
+ createdAt: row.createdAt,
57
+ }));
58
+ },
59
+ });
60
+
34
61
  /** A subject's sticky assignment for an experiment, or `null` if not enrolled. */
35
62
  export const getAssignment = query({
36
63
  args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
@@ -53,32 +80,82 @@ export const getAssignment = query({
53
80
  });
54
81
 
55
82
  /**
56
- * Per-variant exposure tallies for an experiment: distinct `subjects` exposed and
57
- * total `exposures`. Reads the deduped exposure rows via the `by_scope_experiment`
58
- * index and groups them in memory (one indexed scan, no per-row queries). An
59
- * experiment with no exposures returns an empty array.
83
+ * Read-only deterministic variant for a subject — the sticky variant **without
84
+ * persisting** anything. Returns the stored assignment if one exists, otherwise
85
+ * the deterministic `pickVariant` result; `{ variant: null }` when the experiment
86
+ * is absent or not `running`. Use this for SSR / server-component render and as a
87
+ * flicker-free first paint; call the `logExposure` mutation to enroll + tally.
88
+ */
89
+ export const peek = query({
90
+ args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
91
+ returns: exposureResult,
92
+ handler: async (ctx, args) => {
93
+ const experiment = await ctx.db
94
+ .query("experiments")
95
+ .withIndex("by_scope_key", (q) =>
96
+ q.eq("scope", args.scope).eq("key", args.key),
97
+ )
98
+ .unique();
99
+ if (experiment === null || experiment.status !== "running") {
100
+ return { variant: null };
101
+ }
102
+ const assignment = await ctx.db
103
+ .query("assignments")
104
+ .withIndex("by_scope_experiment_subject", (q) =>
105
+ q
106
+ .eq("scope", args.scope)
107
+ .eq("experimentKey", args.key)
108
+ .eq("subjectRef", args.subjectRef),
109
+ )
110
+ .unique();
111
+ if (assignment !== null) {
112
+ return { variant: assignment.variant };
113
+ }
114
+ return {
115
+ variant: pickVariant(
116
+ experiment.variants,
117
+ `${experiment.scope}:${experiment.salt}`,
118
+ args.subjectRef,
119
+ ),
120
+ };
121
+ },
122
+ });
123
+
124
+ /**
125
+ * Per-variant tallies for an experiment — `assigned`, distinct `subjects` exposed,
126
+ * total `exposures`, and the configured `weight` (for sample-ratio-mismatch).
127
+ * Reads the maintained `variantTallies` rows (O(variants)), never scanning the
128
+ * exposure table. An experiment with no enrollment returns an empty array.
60
129
  */
61
130
  export const results = query({
62
131
  args: { scope: v.string(), key: v.string() },
63
132
  returns: v.array(variantResult),
64
133
  handler: async (ctx, args) => {
65
- const rows = await ctx.db
66
- .query("exposures")
134
+ const experiment = await ctx.db
135
+ .query("experiments")
136
+ .withIndex("by_scope_key", (q) =>
137
+ q.eq("scope", args.scope).eq("key", args.key),
138
+ )
139
+ .unique();
140
+ if (experiment === null) {
141
+ return [];
142
+ }
143
+ const tallies = await ctx.db
144
+ .query("variantTallies")
67
145
  .withIndex("by_scope_experiment", (q) =>
68
146
  q.eq("scope", args.scope).eq("experimentKey", args.key),
69
147
  )
70
148
  .collect();
71
- const byVariant = new Map<string, { subjects: number; exposures: number }>();
72
- for (const row of rows) {
73
- const agg = byVariant.get(row.variant) ?? { subjects: 0, exposures: 0 };
74
- agg.subjects += 1;
75
- agg.exposures += row.count;
76
- byVariant.set(row.variant, agg);
77
- }
78
- return Array.from(byVariant, ([variantKey, agg]) => ({
79
- variant: variantKey,
80
- subjects: agg.subjects,
81
- exposures: agg.exposures,
82
- }));
149
+ const byVariant = new Map(tallies.map((tally) => [tally.variant, tally]));
150
+ return experiment.variants.map((variant) => {
151
+ const tally = byVariant.get(variant.key);
152
+ return {
153
+ variant: variant.key,
154
+ assigned: tally?.assigned ?? 0,
155
+ subjects: tally?.subjects ?? 0,
156
+ exposures: tally?.exposures ?? 0,
157
+ weight: variant.weight,
158
+ };
159
+ });
83
160
  },
84
161
  });
@@ -1,15 +1,18 @@
1
1
  import { defineSchema, defineTable } from "convex/server";
2
2
  import { v } from "convex/values";
3
- import { variant } from "./validators";
3
+ import { variant } from "./validators.js";
4
4
 
5
5
  /**
6
6
  * Sandboxed tables — the experimentation ledger's own concern. No host tables are
7
7
  * touched. An experiment is unique within a `scope`; `subjectRef`, variant keys,
8
8
  * and the scope are all opaque host-owned strings.
9
9
  *
10
- * - `experiments` — the experiment definition (variants, weights, lifecycle, salt).
11
- * - `assignments` — a subject's sticky variant choice, persisted on first `assign`.
12
- * - `exposures` — a deduped per-subject exposure tally (the measurable surface).
10
+ * - `experiments` — the experiment definition (variants, weights, lifecycle, salt).
11
+ * - `assignments` — a subject's sticky variant choice, persisted on first `assign`.
12
+ * - `exposures` — a deduped per-subject exposure tally (the measurable surface).
13
+ * - `variantTallies` — one row per `(scope, experiment, variant)` holding running
14
+ * `assigned` / `subjects` (distinct exposed) / `exposures` counts, maintained on
15
+ * write so `results` reads O(variants) rows instead of scanning every exposure.
13
16
  */
14
17
  export default defineSchema({
15
18
  experiments: defineTable({
@@ -23,7 +26,9 @@ export default defineSchema({
23
26
  variants: v.array(variant),
24
27
  salt: v.string(),
25
28
  createdAt: v.number(),
26
- }).index("by_scope_key", ["scope", "key"]),
29
+ })
30
+ .index("by_scope_key", ["scope", "key"])
31
+ .index("by_scope", ["scope"]),
27
32
 
28
33
  assignments: defineTable({
29
34
  scope: v.string(),
@@ -52,4 +57,15 @@ export default defineSchema({
52
57
  "subjectRef",
53
58
  ])
54
59
  .index("by_scope_experiment", ["scope", "experimentKey"]),
60
+
61
+ variantTallies: defineTable({
62
+ scope: v.string(),
63
+ experimentKey: v.string(),
64
+ variant: v.string(),
65
+ assigned: v.number(),
66
+ subjects: v.number(),
67
+ exposures: v.number(),
68
+ })
69
+ .index("by_scope_experiment_variant", ["scope", "experimentKey", "variant"])
70
+ .index("by_scope_experiment", ["scope", "experimentKey"]),
55
71
  });
@@ -21,13 +21,16 @@ export const assignResult = v.union(
21
21
  v.object({ variant: v.string(), isNew: v.boolean() }),
22
22
  );
23
23
 
24
- /** Result of `logExposure`: the enrolled variant, or `null` when not enrolled. */
24
+ /**
25
+ * Result of `logExposure` / `peek`: the enrolled variant, or `null` when the
26
+ * subject is not enrolled (experiment absent or not `running`).
27
+ */
25
28
  export const exposureResult = v.union(
26
29
  v.object({ variant: v.null() }),
27
30
  v.object({ variant: v.string() }),
28
31
  );
29
32
 
30
- /** Projection of an experiment definition returned by `getExperiment`. */
33
+ /** Projection of an experiment definition returned by `getExperiment` / `listExperiments`. */
31
34
  export const experimentDef = v.object({
32
35
  key: v.string(),
33
36
  scope: v.string(),
@@ -43,12 +46,20 @@ export const assignmentProjection = v.object({
43
46
  assignedAt: v.number(),
44
47
  });
45
48
 
46
- /** Per-variant exposure tally returned by `results`. */
49
+ /**
50
+ * Per-variant tally returned by `results`. `assigned` and `subjects` together with
51
+ * the configured `weight` let an analyst compute sample-ratio-mismatch (observed
52
+ * vs expected split) and the funnel denominator host-side.
53
+ */
47
54
  export const variantResult = v.object({
48
55
  /** The variant key. */
49
56
  variant: v.string(),
57
+ /** Subjects assigned to this variant (the realized split for SRM). */
58
+ assigned: v.number(),
50
59
  /** Distinct subjects exposed to this variant (the funnel denominator). */
51
60
  subjects: v.number(),
52
61
  /** Total exposure events recorded for this variant. */
53
62
  exposures: v.number(),
63
+ /** The configured weight from the current definition (0 if the variant is gone). */
64
+ weight: v.number(),
54
65
  });