@vllnt/convex-experiments 0.1.0-canary.1c87af5

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 (71) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +161 -0
  3. package/dist/client/index.d.ts +168 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +154 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/types.d.ts +75 -0
  8. package/dist/client/types.d.ts.map +1 -0
  9. package/dist/client/types.js +3 -0
  10. package/dist/client/types.js.map +1 -0
  11. package/dist/component/_generated/api.d.ts +38 -0
  12. package/dist/component/_generated/api.d.ts.map +1 -0
  13. package/dist/component/_generated/api.js +31 -0
  14. package/dist/component/_generated/api.js.map +1 -0
  15. package/dist/component/_generated/component.d.ts +128 -0
  16. package/dist/component/_generated/component.d.ts.map +1 -0
  17. package/dist/component/_generated/component.js +11 -0
  18. package/dist/component/_generated/component.js.map +1 -0
  19. package/dist/component/_generated/dataModel.d.ts +46 -0
  20. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  21. package/dist/component/_generated/dataModel.js +11 -0
  22. package/dist/component/_generated/dataModel.js.map +1 -0
  23. package/dist/component/_generated/server.d.ts +121 -0
  24. package/dist/component/_generated/server.d.ts.map +1 -0
  25. package/dist/component/_generated/server.js +78 -0
  26. package/dist/component/_generated/server.js.map +1 -0
  27. package/dist/component/convex.config.d.ts +3 -0
  28. package/dist/component/convex.config.d.ts.map +1 -0
  29. package/dist/component/convex.config.js +7 -0
  30. package/dist/component/convex.config.js.map +1 -0
  31. package/dist/component/mutations.d.ts +93 -0
  32. package/dist/component/mutations.d.ts.map +1 -0
  33. package/dist/component/mutations.js +359 -0
  34. package/dist/component/mutations.js.map +1 -0
  35. package/dist/component/queries.d.ts +72 -0
  36. package/dist/component/queries.d.ts.map +1 -0
  37. package/dist/component/queries.js +134 -0
  38. package/dist/component/queries.js.map +1 -0
  39. package/dist/component/schema.d.ts +99 -0
  40. package/dist/component/schema.d.ts.map +1 -0
  41. package/dist/component/schema.js +64 -0
  42. package/dist/component/schema.js.map +1 -0
  43. package/dist/component/validators.d.ts +109 -0
  44. package/dist/component/validators.d.ts.map +1 -0
  45. package/dist/component/validators.js +49 -0
  46. package/dist/component/validators.js.map +1 -0
  47. package/dist/react/index.d.ts +57 -0
  48. package/dist/react/index.d.ts.map +1 -0
  49. package/dist/react/index.js +39 -0
  50. package/dist/react/index.js.map +1 -0
  51. package/dist/shared.d.ts +32 -0
  52. package/dist/shared.d.ts.map +1 -0
  53. package/dist/shared.js +52 -0
  54. package/dist/shared.js.map +1 -0
  55. package/package.json +115 -0
  56. package/src/client/index.ts +343 -0
  57. package/src/client/types.ts +78 -0
  58. package/src/component/_generated/api.ts +54 -0
  59. package/src/component/_generated/component.ts +133 -0
  60. package/src/component/_generated/dataModel.ts +60 -0
  61. package/src/component/_generated/server.ts +156 -0
  62. package/src/component/convex.config.ts +9 -0
  63. package/src/component/mutations.ts +414 -0
  64. package/src/component/queries.ts +161 -0
  65. package/src/component/schema.ts +71 -0
  66. package/src/component/validators.ts +65 -0
  67. package/src/react/index.test.tsx +85 -0
  68. package/src/react/index.tsx +68 -0
  69. package/src/shared.ts +69 -0
  70. package/src/test.ts +12 -0
  71. package/src/unit.test.ts +84 -0
@@ -0,0 +1,414 @@
1
+ import { ConvexError, v } from "convex/values";
2
+ import { api } from "./_generated/api";
3
+ import type { Doc } from "./_generated/dataModel";
4
+ import type { MutationCtx } from "./_generated/server";
5
+ import { mutation } from "./_generated/server";
6
+ import { pickVariant, type Variant } from "../shared";
7
+ import { assignResult, experimentStatus, exposureResult, variant } from "./validators";
8
+
9
+ /**
10
+ * Reject a malformed variant set before any write: at least one variant, every
11
+ * weight a positive finite number, and no duplicate variant keys. The thrown
12
+ * `ConvexError` carries a `reason` so the host can branch on the specific failure.
13
+ *
14
+ * @throws `ConvexError({ code: "INVALID_VARIANTS", reason })`
15
+ */
16
+ function validateVariants(variants: readonly Variant[]): void {
17
+ if (variants.length === 0) {
18
+ throw new ConvexError({
19
+ code: "INVALID_VARIANTS",
20
+ reason: "empty",
21
+ message: "an experiment needs at least one variant",
22
+ });
23
+ }
24
+ const seen = new Set<string>();
25
+ for (const candidate of variants) {
26
+ if (!(candidate.weight > 0 && isFinite(candidate.weight))) {
27
+ throw new ConvexError({
28
+ code: "INVALID_VARIANTS",
29
+ reason: "non_positive_weight",
30
+ key: candidate.key,
31
+ message: `variant "${candidate.key}" weight must be a positive finite number`,
32
+ });
33
+ }
34
+ if (seen.has(candidate.key)) {
35
+ throw new ConvexError({
36
+ code: "INVALID_VARIANTS",
37
+ reason: "duplicate_key",
38
+ key: candidate.key,
39
+ message: `duplicate variant key "${candidate.key}"`,
40
+ });
41
+ }
42
+ seen.add(candidate.key);
43
+ }
44
+ }
45
+
46
+ /**
47
+ * The hash salt for an experiment folds in `scope` so the same `subjectRef` lands
48
+ * in an independent bucket per scope (a tenant-correlation bug otherwise) and the
49
+ * host's `salt` re-keys within the scope.
50
+ */
51
+ function hashSalt(experiment: Doc<"experiments">): string {
52
+ return `${experiment.scope}:${experiment.salt}`;
53
+ }
54
+
55
+ /** Incrementally maintain the per-`(scope, experiment, variant)` tally row. */
56
+ async function bumpTally(
57
+ ctx: MutationCtx,
58
+ scope: string,
59
+ experimentKey: string,
60
+ variantKey: string,
61
+ delta: { assigned?: number; subjects?: number; exposures?: number },
62
+ ): Promise<void> {
63
+ const assigned = delta.assigned ?? 0;
64
+ const subjects = delta.subjects ?? 0;
65
+ const exposures = delta.exposures ?? 0;
66
+ const row = await ctx.db
67
+ .query("variantTallies")
68
+ .withIndex("by_scope_experiment_variant", (q) =>
69
+ q.eq("scope", scope).eq("experimentKey", experimentKey).eq("variant", variantKey),
70
+ )
71
+ .unique();
72
+ if (row === null) {
73
+ await ctx.db.insert("variantTallies", {
74
+ scope,
75
+ experimentKey,
76
+ variant: variantKey,
77
+ assigned,
78
+ subjects,
79
+ exposures,
80
+ });
81
+ } else {
82
+ await ctx.db.patch(row._id, {
83
+ assigned: row.assigned + assigned,
84
+ subjects: row.subjects + subjects,
85
+ exposures: row.exposures + exposures,
86
+ });
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Return the subject's sticky assignment, persisting a fresh deterministic pick on
92
+ * first sight (and bumping the variant's `assigned` tally). Plain helper (not a
93
+ * Convex function) so `assign` and `logExposure` share one enrollment path. Time is
94
+ * server-sourced by the caller.
95
+ */
96
+ async function ensureAssignment(
97
+ ctx: MutationCtx,
98
+ experiment: Doc<"experiments">,
99
+ subjectRef: string,
100
+ now: number,
101
+ ): Promise<{ variant: string; isNew: boolean }> {
102
+ const existing = await ctx.db
103
+ .query("assignments")
104
+ .withIndex("by_scope_experiment_subject", (q) =>
105
+ q
106
+ .eq("scope", experiment.scope)
107
+ .eq("experimentKey", experiment.key)
108
+ .eq("subjectRef", subjectRef),
109
+ )
110
+ .unique();
111
+ if (existing !== null) {
112
+ return { variant: existing.variant, isNew: false };
113
+ }
114
+ const variantKey = pickVariant(experiment.variants, hashSalt(experiment), subjectRef);
115
+ await ctx.db.insert("assignments", {
116
+ scope: experiment.scope,
117
+ experimentKey: experiment.key,
118
+ subjectRef,
119
+ variant: variantKey,
120
+ assignedAt: now,
121
+ });
122
+ await bumpTally(ctx, experiment.scope, experiment.key, variantKey, { assigned: 1 });
123
+ return { variant: variantKey, isNew: true };
124
+ }
125
+
126
+ /** True when two variant sets differ in key, weight, or order. */
127
+ function variantsChanged(a: readonly Variant[], b: readonly Variant[]): boolean {
128
+ return JSON.stringify(a) !== JSON.stringify(b);
129
+ }
130
+
131
+ /**
132
+ * Create or update an experiment definition, keyed by `(scope, key)`. Returns
133
+ * `{ created: true }` on insert, `{ created: false }` on update. Time is
134
+ * server-sourced.
135
+ *
136
+ * **Immutability once assigned:** `variants` and `salt` are fixed once any subject
137
+ * is assigned — changing them would split the population across two randomizations
138
+ * (some subjects bucketed under the old definition, some the new) and orphan
139
+ * tallies. Status transitions (start/stop) are always allowed. To re-randomize or
140
+ * reweight after enrollment, define a new experiment key.
141
+ *
142
+ * @throws `ConvexError({ code: "INVALID_VARIANTS", reason })` for a bad variant set.
143
+ * @throws `ConvexError({ code: "EXPERIMENT_LOCKED" })` when `variants`/`salt` change
144
+ * after a subject has been assigned.
145
+ */
146
+ export const define = mutation({
147
+ args: {
148
+ scope: v.string(),
149
+ key: v.string(),
150
+ variants: v.array(variant),
151
+ salt: v.string(),
152
+ status: experimentStatus,
153
+ },
154
+ returns: v.object({ created: v.boolean() }),
155
+ handler: async (ctx, args) => {
156
+ validateVariants(args.variants);
157
+ const existing = await ctx.db
158
+ .query("experiments")
159
+ .withIndex("by_scope_key", (q) =>
160
+ q.eq("scope", args.scope).eq("key", args.key),
161
+ )
162
+ .unique();
163
+ if (existing === null) {
164
+ await ctx.db.insert("experiments", {
165
+ key: args.key,
166
+ scope: args.scope,
167
+ status: args.status,
168
+ variants: args.variants,
169
+ salt: args.salt,
170
+ createdAt: Date.now(),
171
+ });
172
+ return { created: true };
173
+ }
174
+ if (variantsChanged(existing.variants, args.variants) || existing.salt !== args.salt) {
175
+ const firstAssignment = await ctx.db
176
+ .query("assignments")
177
+ .withIndex("by_scope_experiment_subject", (q) =>
178
+ q.eq("scope", args.scope).eq("experimentKey", args.key),
179
+ )
180
+ .first();
181
+ if (firstAssignment !== null) {
182
+ throw new ConvexError({
183
+ code: "EXPERIMENT_LOCKED",
184
+ message:
185
+ "variants and salt are immutable once subjects are assigned; define a new experiment key to re-randomize",
186
+ });
187
+ }
188
+ }
189
+ await ctx.db.patch(existing._id, {
190
+ status: args.status,
191
+ variants: args.variants,
192
+ salt: args.salt,
193
+ });
194
+ return { created: false };
195
+ },
196
+ });
197
+
198
+ /**
199
+ * Move an experiment to a new lifecycle `status`. Returns `false` when no
200
+ * experiment exists for `(scope, key)`, `true` once patched. Stopping an
201
+ * experiment freezes enrollment (`assign` returns `{ variant: null }`) while
202
+ * leaving recorded assignments and exposures intact.
203
+ */
204
+ export const setStatus = mutation({
205
+ args: { scope: v.string(), key: v.string(), status: experimentStatus },
206
+ returns: v.boolean(),
207
+ handler: async (ctx, args) => {
208
+ const existing = await ctx.db
209
+ .query("experiments")
210
+ .withIndex("by_scope_key", (q) =>
211
+ q.eq("scope", args.scope).eq("key", args.key),
212
+ )
213
+ .unique();
214
+ if (existing === null) {
215
+ return false;
216
+ }
217
+ await ctx.db.patch(existing._id, { status: args.status });
218
+ return true;
219
+ },
220
+ });
221
+
222
+ /**
223
+ * Enroll `subjectRef` and return the sticky variant. `{ variant: null }` when the
224
+ * experiment is absent or not `running` (the host treats it as control). When
225
+ * `running`, the first call deterministically picks and persists a variant
226
+ * (`isNew: true`); later calls replay it (`isNew: false`). Time is server-sourced.
227
+ */
228
+ export const assign = mutation({
229
+ args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
230
+ returns: assignResult,
231
+ handler: async (ctx, args) => {
232
+ const experiment = await ctx.db
233
+ .query("experiments")
234
+ .withIndex("by_scope_key", (q) =>
235
+ q.eq("scope", args.scope).eq("key", args.key),
236
+ )
237
+ .unique();
238
+ if (experiment === null || experiment.status !== "running") {
239
+ return { variant: null };
240
+ }
241
+ return ensureAssignment(ctx, experiment, args.subjectRef, Date.now());
242
+ },
243
+ });
244
+
245
+ /**
246
+ * Record that `subjectRef` was exposed and return their variant, enrolling if
247
+ * needed. First exposure inserts a tally row and bumps `subjects` + `exposures`;
248
+ * later exposures bump `exposures` only (deduped per subject). `{ variant: null }`
249
+ * when not enrolled. Time is server-sourced.
250
+ */
251
+ export const logExposure = mutation({
252
+ args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
253
+ returns: exposureResult,
254
+ handler: async (ctx, args) => {
255
+ const experiment = await ctx.db
256
+ .query("experiments")
257
+ .withIndex("by_scope_key", (q) =>
258
+ q.eq("scope", args.scope).eq("key", args.key),
259
+ )
260
+ .unique();
261
+ if (experiment === null || experiment.status !== "running") {
262
+ return { variant: null };
263
+ }
264
+ const now = Date.now();
265
+ const { variant: variantKey } = await ensureAssignment(
266
+ ctx,
267
+ experiment,
268
+ args.subjectRef,
269
+ now,
270
+ );
271
+ const existing = await ctx.db
272
+ .query("exposures")
273
+ .withIndex("by_scope_experiment_subject", (q) =>
274
+ q
275
+ .eq("scope", args.scope)
276
+ .eq("experimentKey", args.key)
277
+ .eq("subjectRef", args.subjectRef),
278
+ )
279
+ .unique();
280
+ if (existing === null) {
281
+ await ctx.db.insert("exposures", {
282
+ scope: args.scope,
283
+ experimentKey: args.key,
284
+ subjectRef: args.subjectRef,
285
+ variant: variantKey,
286
+ firstExposedAt: now,
287
+ lastExposedAt: now,
288
+ count: 1,
289
+ });
290
+ await bumpTally(ctx, args.scope, args.key, variantKey, {
291
+ subjects: 1,
292
+ exposures: 1,
293
+ });
294
+ } else {
295
+ await ctx.db.patch(existing._id, {
296
+ lastExposedAt: now,
297
+ count: existing.count + 1,
298
+ });
299
+ await bumpTally(ctx, args.scope, args.key, variantKey, { exposures: 1 });
300
+ }
301
+ return { variant: variantKey };
302
+ },
303
+ });
304
+
305
+ /**
306
+ * Erase a subject's footprint in one experiment — their assignment and exposure
307
+ * rows — decrementing the variant tallies accordingly. The GDPR right-to-erasure
308
+ * primitive for a `subjectRef` that maps to a person. Returns `true` if anything
309
+ * was deleted. Loop over `listExperiments` to erase a subject across a scope.
310
+ */
311
+ export const forgetSubject = mutation({
312
+ args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
313
+ returns: v.boolean(),
314
+ handler: async (ctx, args) => {
315
+ let deleted = false;
316
+ const assignment = await ctx.db
317
+ .query("assignments")
318
+ .withIndex("by_scope_experiment_subject", (q) =>
319
+ q
320
+ .eq("scope", args.scope)
321
+ .eq("experimentKey", args.key)
322
+ .eq("subjectRef", args.subjectRef),
323
+ )
324
+ .unique();
325
+ if (assignment !== null) {
326
+ await bumpTally(ctx, args.scope, args.key, assignment.variant, {
327
+ assigned: -1,
328
+ });
329
+ await ctx.db.delete(assignment._id);
330
+ deleted = true;
331
+ }
332
+ const exposure = await ctx.db
333
+ .query("exposures")
334
+ .withIndex("by_scope_experiment_subject", (q) =>
335
+ q
336
+ .eq("scope", args.scope)
337
+ .eq("experimentKey", args.key)
338
+ .eq("subjectRef", args.subjectRef),
339
+ )
340
+ .unique();
341
+ if (exposure !== null) {
342
+ await bumpTally(ctx, args.scope, args.key, exposure.variant, {
343
+ subjects: -1,
344
+ exposures: -exposure.count,
345
+ });
346
+ await ctx.db.delete(exposure._id);
347
+ deleted = true;
348
+ }
349
+ return deleted;
350
+ },
351
+ });
352
+
353
+ /**
354
+ * Delete an experiment and all of its data — the definition, every assignment,
355
+ * exposure, and tally row. Bounded: removes up to `batch` rows per table per pass
356
+ * and self-reschedules until the children are drained, then deletes the definition.
357
+ * Idempotent and safe to call on an absent experiment. Returns the rows removed
358
+ * this pass.
359
+ */
360
+ export const deleteExperiment = mutation({
361
+ args: { scope: v.string(), key: v.string(), batch: v.number() },
362
+ returns: v.number(),
363
+ handler: async (ctx, args) => {
364
+ let removed = 0;
365
+ const assignments = await ctx.db
366
+ .query("assignments")
367
+ .withIndex("by_scope_experiment_subject", (q) =>
368
+ q.eq("scope", args.scope).eq("experimentKey", args.key),
369
+ )
370
+ .take(args.batch);
371
+ for (const row of assignments) {
372
+ await ctx.db.delete(row._id);
373
+ removed++;
374
+ }
375
+ const exposures = await ctx.db
376
+ .query("exposures")
377
+ .withIndex("by_scope_experiment", (q) =>
378
+ q.eq("scope", args.scope).eq("experimentKey", args.key),
379
+ )
380
+ .take(args.batch);
381
+ for (const row of exposures) {
382
+ await ctx.db.delete(row._id);
383
+ removed++;
384
+ }
385
+ const tallies = await ctx.db
386
+ .query("variantTallies")
387
+ .withIndex("by_scope_experiment", (q) =>
388
+ q.eq("scope", args.scope).eq("experimentKey", args.key),
389
+ )
390
+ .take(args.batch);
391
+ for (const row of tallies) {
392
+ await ctx.db.delete(row._id);
393
+ removed++;
394
+ }
395
+ if (removed > 0) {
396
+ await ctx.scheduler.runAfter(0, api.mutations.deleteExperiment, {
397
+ scope: args.scope,
398
+ key: args.key,
399
+ batch: args.batch,
400
+ });
401
+ return removed;
402
+ }
403
+ const def = await ctx.db
404
+ .query("experiments")
405
+ .withIndex("by_scope_key", (q) =>
406
+ q.eq("scope", args.scope).eq("key", args.key),
407
+ )
408
+ .unique();
409
+ if (def !== null) {
410
+ await ctx.db.delete(def._id);
411
+ }
412
+ return removed;
413
+ },
414
+ });
@@ -0,0 +1,161 @@
1
+ import { v } from "convex/values";
2
+ import { query } from "./_generated/server";
3
+ import { pickVariant } from "../shared";
4
+ import {
5
+ assignmentProjection,
6
+ experimentDef,
7
+ experimentStatus,
8
+ exposureResult,
9
+ variantResult,
10
+ } from "./validators";
11
+
12
+ /** The experiment definition for `(scope, key)`, or `null` if none exists. */
13
+ export const getExperiment = query({
14
+ args: { scope: v.string(), key: v.string() },
15
+ returns: v.union(v.null(), experimentDef),
16
+ handler: async (ctx, args) => {
17
+ const row = await ctx.db
18
+ .query("experiments")
19
+ .withIndex("by_scope_key", (q) =>
20
+ q.eq("scope", args.scope).eq("key", args.key),
21
+ )
22
+ .unique();
23
+ if (row === null) {
24
+ return null;
25
+ }
26
+ return {
27
+ key: row.key,
28
+ scope: row.scope,
29
+ status: row.status,
30
+ variants: row.variants,
31
+ salt: row.salt,
32
+ createdAt: row.createdAt,
33
+ };
34
+ },
35
+ });
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
+
61
+ /** A subject's sticky assignment for an experiment, or `null` if not enrolled. */
62
+ export const getAssignment = query({
63
+ args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
64
+ returns: v.union(v.null(), assignmentProjection),
65
+ handler: async (ctx, args) => {
66
+ const row = await ctx.db
67
+ .query("assignments")
68
+ .withIndex("by_scope_experiment_subject", (q) =>
69
+ q
70
+ .eq("scope", args.scope)
71
+ .eq("experimentKey", args.key)
72
+ .eq("subjectRef", args.subjectRef),
73
+ )
74
+ .unique();
75
+ if (row === null) {
76
+ return null;
77
+ }
78
+ return { variant: row.variant, assignedAt: row.assignedAt };
79
+ },
80
+ });
81
+
82
+ /**
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.
129
+ */
130
+ export const results = query({
131
+ args: { scope: v.string(), key: v.string() },
132
+ returns: v.array(variantResult),
133
+ handler: async (ctx, args) => {
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")
145
+ .withIndex("by_scope_experiment", (q) =>
146
+ q.eq("scope", args.scope).eq("experimentKey", args.key),
147
+ )
148
+ .collect();
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
+ });
160
+ },
161
+ });
@@ -0,0 +1,71 @@
1
+ import { defineSchema, defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+ import { variant } from "./validators";
4
+
5
+ /**
6
+ * Sandboxed tables — the experimentation ledger's own concern. No host tables are
7
+ * touched. An experiment is unique within a `scope`; `subjectRef`, variant keys,
8
+ * and the scope are all opaque host-owned strings.
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).
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.
16
+ */
17
+ export default defineSchema({
18
+ experiments: defineTable({
19
+ key: v.string(),
20
+ scope: v.string(),
21
+ status: v.union(
22
+ v.literal("draft"),
23
+ v.literal("running"),
24
+ v.literal("stopped"),
25
+ ),
26
+ variants: v.array(variant),
27
+ salt: v.string(),
28
+ createdAt: v.number(),
29
+ })
30
+ .index("by_scope_key", ["scope", "key"])
31
+ .index("by_scope", ["scope"]),
32
+
33
+ assignments: defineTable({
34
+ scope: v.string(),
35
+ experimentKey: v.string(),
36
+ subjectRef: v.string(),
37
+ variant: v.string(),
38
+ assignedAt: v.number(),
39
+ }).index("by_scope_experiment_subject", [
40
+ "scope",
41
+ "experimentKey",
42
+ "subjectRef",
43
+ ]),
44
+
45
+ exposures: defineTable({
46
+ scope: v.string(),
47
+ experimentKey: v.string(),
48
+ subjectRef: v.string(),
49
+ variant: v.string(),
50
+ firstExposedAt: v.number(),
51
+ lastExposedAt: v.number(),
52
+ count: v.number(),
53
+ })
54
+ .index("by_scope_experiment_subject", [
55
+ "scope",
56
+ "experimentKey",
57
+ "subjectRef",
58
+ ])
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"]),
71
+ });