@vllnt/convex-experiments 0.1.0-canary.f2cd1ba → 0.1.0
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.
- package/README.md +35 -6
- package/dist/client/index.d.ts +54 -3
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +53 -4
- package/dist/client/index.js.map +1 -1
- package/dist/client/types.d.ts +8 -3
- package/dist/client/types.d.ts.map +1 -1
- package/dist/component/_generated/component.d.ts +35 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/_generated/server.d.ts +12 -0
- package/dist/component/_generated/server.d.ts.map +1 -1
- package/dist/component/_generated/server.js +2 -0
- package/dist/component/_generated/server.js.map +1 -1
- package/dist/component/convex.config.d.ts.map +1 -1
- package/dist/component/mutations.d.ts +46 -20
- package/dist/component/mutations.d.ts.map +1 -1
- package/dist/component/mutations.js +192 -23
- package/dist/component/mutations.js.map +1 -1
- package/dist/component/queries.d.ts +41 -8
- package/dist/component/queries.d.ts.map +1 -1
- package/dist/component/queries.js +81 -19
- package/dist/component/queries.js.map +1 -1
- package/dist/component/schema.d.ts +39 -17
- package/dist/component/schema.d.ts.map +1 -1
- package/dist/component/schema.js +19 -4
- package/dist/component/schema.js.map +1 -1
- package/dist/component/validators.d.ts +31 -18
- package/dist/component/validators.d.ts.map +1 -1
- package/dist/component/validators.js +14 -3
- package/dist/component/validators.js.map +1 -1
- package/dist/react/index.d.ts +57 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +39 -0
- package/dist/react/index.js.map +1 -0
- package/dist/shared.d.ts +5 -3
- package/dist/shared.d.ts.map +1 -1
- package/dist/shared.js +5 -3
- package/dist/shared.js.map +1 -1
- package/package.json +34 -15
- package/src/client/index.ts +98 -4
- package/src/client/types.ts +8 -3
- package/src/component/_generated/component.ts +42 -1
- package/src/component/_generated/server.ts +13 -0
- package/src/component/mutations.ts +219 -23
- package/src/component/queries.ts +95 -18
- package/src/component/schema.ts +20 -4
- package/src/component/validators.ts +14 -3
- package/src/react/index.test.tsx +85 -0
- package/src/react/index.tsx +68 -0
- package/src/shared.ts +6 -3
package/src/client/index.ts
CHANGED
|
@@ -14,7 +14,7 @@ import type {
|
|
|
14
14
|
Variant,
|
|
15
15
|
VariantResult,
|
|
16
16
|
} from "./types.js";
|
|
17
|
-
import { DEFAULT_SCOPE, DEFAULT_STATUS } from "../shared.js";
|
|
17
|
+
import { DEFAULT_DELETE_BATCH, DEFAULT_SCOPE, DEFAULT_STATUS } from "../shared.js";
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
20
|
* The experiments component's function references, as exposed on the host via
|
|
@@ -53,6 +53,18 @@ export interface ExperimentsComponent {
|
|
|
53
53
|
{ scope: string; key: string; subjectRef: string },
|
|
54
54
|
ExposureOutcome
|
|
55
55
|
>;
|
|
56
|
+
forgetSubject: FunctionReference<
|
|
57
|
+
"mutation",
|
|
58
|
+
"internal",
|
|
59
|
+
{ scope: string; key: string; subjectRef: string },
|
|
60
|
+
boolean
|
|
61
|
+
>;
|
|
62
|
+
deleteExperiment: FunctionReference<
|
|
63
|
+
"mutation",
|
|
64
|
+
"internal",
|
|
65
|
+
{ scope: string; key: string; batch: number },
|
|
66
|
+
number
|
|
67
|
+
>;
|
|
56
68
|
};
|
|
57
69
|
queries: {
|
|
58
70
|
getExperiment: FunctionReference<
|
|
@@ -61,12 +73,24 @@ export interface ExperimentsComponent {
|
|
|
61
73
|
{ scope: string; key: string },
|
|
62
74
|
ExperimentDefinition | null
|
|
63
75
|
>;
|
|
76
|
+
listExperiments: FunctionReference<
|
|
77
|
+
"query",
|
|
78
|
+
"internal",
|
|
79
|
+
{ scope: string; status?: ExperimentStatus },
|
|
80
|
+
ExperimentDefinition[]
|
|
81
|
+
>;
|
|
64
82
|
getAssignment: FunctionReference<
|
|
65
83
|
"query",
|
|
66
84
|
"internal",
|
|
67
85
|
{ scope: string; key: string; subjectRef: string },
|
|
68
86
|
Assignment | null
|
|
69
87
|
>;
|
|
88
|
+
peek: FunctionReference<
|
|
89
|
+
"query",
|
|
90
|
+
"internal",
|
|
91
|
+
{ scope: string; key: string; subjectRef: string },
|
|
92
|
+
ExposureOutcome
|
|
93
|
+
>;
|
|
70
94
|
results: FunctionReference<
|
|
71
95
|
"query",
|
|
72
96
|
"internal",
|
|
@@ -130,8 +154,9 @@ export class Experiments {
|
|
|
130
154
|
/**
|
|
131
155
|
* Create or update an experiment. `variants` are weighted (equal weights split
|
|
132
156
|
* evenly). `salt` defaults to `key`; `status` to the client default (`running`).
|
|
133
|
-
* Returns `{ created }` — `false` when an existing definition was updated.
|
|
134
|
-
*
|
|
157
|
+
* Returns `{ created }` — `false` when an existing definition was updated. Status
|
|
158
|
+
* transitions are always allowed; `variants`/`salt` are immutable once a subject
|
|
159
|
+
* is assigned (throws `EXPERIMENT_LOCKED`).
|
|
135
160
|
*/
|
|
136
161
|
define(
|
|
137
162
|
ctx: RunMutationCtx,
|
|
@@ -223,7 +248,41 @@ export class Experiments {
|
|
|
223
248
|
});
|
|
224
249
|
}
|
|
225
250
|
|
|
226
|
-
/**
|
|
251
|
+
/**
|
|
252
|
+
* Read-only deterministic variant for a subject — the sticky variant **without
|
|
253
|
+
* persisting**. Returns the stored assignment if present, else the deterministic
|
|
254
|
+
* pick; `null` when not enrolled. Use for SSR / a flicker-free first paint, then
|
|
255
|
+
* call `logExposure` to enroll + tally.
|
|
256
|
+
*/
|
|
257
|
+
peek(
|
|
258
|
+
ctx: RunQueryCtx,
|
|
259
|
+
key: string,
|
|
260
|
+
subjectRef: string,
|
|
261
|
+
scope?: string,
|
|
262
|
+
): Promise<ExposureOutcome> {
|
|
263
|
+
return ctx.runQuery(this.component.queries.peek, {
|
|
264
|
+
scope: this.scopeOf(scope),
|
|
265
|
+
key,
|
|
266
|
+
subjectRef,
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Every experiment in a scope, optionally filtered by `status`. */
|
|
271
|
+
listExperiments(
|
|
272
|
+
ctx: RunQueryCtx,
|
|
273
|
+
opts: { scope?: string; status?: ExperimentStatus } = {},
|
|
274
|
+
): Promise<ExperimentDefinition[]> {
|
|
275
|
+
return ctx.runQuery(this.component.queries.listExperiments, {
|
|
276
|
+
scope: this.scopeOf(opts.scope),
|
|
277
|
+
status: opts.status,
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Per-variant tallies — `assigned`, distinct `subjects` exposed, total
|
|
283
|
+
* `exposures`, and the configured `weight` (for sample-ratio-mismatch). Reads
|
|
284
|
+
* O(variants), not the exposure table.
|
|
285
|
+
*/
|
|
227
286
|
results(
|
|
228
287
|
ctx: RunQueryCtx,
|
|
229
288
|
key: string,
|
|
@@ -234,6 +293,41 @@ export class Experiments {
|
|
|
234
293
|
key,
|
|
235
294
|
});
|
|
236
295
|
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Erase a subject's assignment + exposure in one experiment (GDPR right-to-
|
|
299
|
+
* erasure), decrementing tallies. Returns `true` if anything was deleted. Loop
|
|
300
|
+
* over `listExperiments` to erase a subject across a whole scope.
|
|
301
|
+
*/
|
|
302
|
+
forgetSubject(
|
|
303
|
+
ctx: RunMutationCtx,
|
|
304
|
+
key: string,
|
|
305
|
+
subjectRef: string,
|
|
306
|
+
scope?: string,
|
|
307
|
+
): Promise<boolean> {
|
|
308
|
+
return ctx.runMutation(this.component.mutations.forgetSubject, {
|
|
309
|
+
scope: this.scopeOf(scope),
|
|
310
|
+
key,
|
|
311
|
+
subjectRef,
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Delete an experiment and all of its data (definition, assignments, exposures,
|
|
317
|
+
* tallies). Bounded + self-rescheduling; returns the rows removed this pass.
|
|
318
|
+
* Idempotent and safe on an absent experiment.
|
|
319
|
+
*/
|
|
320
|
+
deleteExperiment(
|
|
321
|
+
ctx: RunMutationCtx,
|
|
322
|
+
key: string,
|
|
323
|
+
opts: { scope?: string; batch?: number } = {},
|
|
324
|
+
): Promise<number> {
|
|
325
|
+
return ctx.runMutation(this.component.mutations.deleteExperiment, {
|
|
326
|
+
scope: this.scopeOf(opts.scope),
|
|
327
|
+
key,
|
|
328
|
+
batch: opts.batch ?? DEFAULT_DELETE_BATCH,
|
|
329
|
+
});
|
|
330
|
+
}
|
|
237
331
|
}
|
|
238
332
|
|
|
239
333
|
export type {
|
package/src/client/types.ts
CHANGED
|
@@ -24,8 +24,9 @@ export interface DefineOptions {
|
|
|
24
24
|
/** Namespace for this experiment. Defaults to the client `defaultScope`. */
|
|
25
25
|
scope?: string;
|
|
26
26
|
/**
|
|
27
|
-
* Hash salt for deterministic assignment. Defaults to the experiment `key
|
|
28
|
-
*
|
|
27
|
+
* Hash salt for deterministic assignment. Defaults to the experiment `key`.
|
|
28
|
+
* Fixed once any subject is assigned (changing it after enrollment throws
|
|
29
|
+
* `EXPERIMENT_LOCKED`); to re-randomize, define a new experiment key.
|
|
29
30
|
*/
|
|
30
31
|
salt?: string;
|
|
31
32
|
/** Initial lifecycle status. Defaults to the client `defaultStatus`. */
|
|
@@ -62,12 +63,16 @@ export type AssignOutcome =
|
|
|
62
63
|
/** Outcome of {@link Experiments.logExposure}: the variant, or `null` if not enrolled. */
|
|
63
64
|
export type ExposureOutcome = { variant: string | null };
|
|
64
65
|
|
|
65
|
-
/** A per-variant
|
|
66
|
+
/** A per-variant tally, as returned by {@link Experiments.results}. */
|
|
66
67
|
export interface VariantResult {
|
|
67
68
|
/** The variant key. */
|
|
68
69
|
variant: string;
|
|
70
|
+
/** Subjects assigned to this variant (the realized split, for SRM). */
|
|
71
|
+
assigned: number;
|
|
69
72
|
/** Distinct subjects exposed to this variant (the funnel denominator). */
|
|
70
73
|
subjects: number;
|
|
71
74
|
/** Total exposure events recorded for this variant. */
|
|
72
75
|
exposures: number;
|
|
76
|
+
/** The configured weight from the current definition (0 if the variant is gone). */
|
|
77
|
+
weight: number;
|
|
73
78
|
}
|
|
@@ -44,6 +44,20 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
|
|
|
44
44
|
{ created: boolean },
|
|
45
45
|
Name
|
|
46
46
|
>;
|
|
47
|
+
deleteExperiment: FunctionReference<
|
|
48
|
+
"mutation",
|
|
49
|
+
"internal",
|
|
50
|
+
{ batch: number; key: string; scope: string },
|
|
51
|
+
number,
|
|
52
|
+
Name
|
|
53
|
+
>;
|
|
54
|
+
forgetSubject: FunctionReference<
|
|
55
|
+
"mutation",
|
|
56
|
+
"internal",
|
|
57
|
+
{ key: string; scope: string; subjectRef: string },
|
|
58
|
+
boolean,
|
|
59
|
+
Name
|
|
60
|
+
>;
|
|
47
61
|
logExposure: FunctionReference<
|
|
48
62
|
"mutation",
|
|
49
63
|
"internal",
|
|
@@ -81,11 +95,38 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
|
|
|
81
95
|
},
|
|
82
96
|
Name
|
|
83
97
|
>;
|
|
98
|
+
listExperiments: FunctionReference<
|
|
99
|
+
"query",
|
|
100
|
+
"internal",
|
|
101
|
+
{ scope: string; status?: "draft" | "running" | "stopped" },
|
|
102
|
+
Array<{
|
|
103
|
+
createdAt: number;
|
|
104
|
+
key: string;
|
|
105
|
+
salt: string;
|
|
106
|
+
scope: string;
|
|
107
|
+
status: "draft" | "running" | "stopped";
|
|
108
|
+
variants: Array<{ key: string; weight: number }>;
|
|
109
|
+
}>,
|
|
110
|
+
Name
|
|
111
|
+
>;
|
|
112
|
+
peek: FunctionReference<
|
|
113
|
+
"query",
|
|
114
|
+
"internal",
|
|
115
|
+
{ key: string; scope: string; subjectRef: string },
|
|
116
|
+
{ variant: null } | { variant: string },
|
|
117
|
+
Name
|
|
118
|
+
>;
|
|
84
119
|
results: FunctionReference<
|
|
85
120
|
"query",
|
|
86
121
|
"internal",
|
|
87
122
|
{ key: string; scope: string },
|
|
88
|
-
Array<{
|
|
123
|
+
Array<{
|
|
124
|
+
assigned: number;
|
|
125
|
+
exposures: number;
|
|
126
|
+
subjects: number;
|
|
127
|
+
variant: string;
|
|
128
|
+
weight: number;
|
|
129
|
+
}>,
|
|
89
130
|
Name
|
|
90
131
|
>;
|
|
91
132
|
};
|
|
@@ -30,6 +30,17 @@ import {
|
|
|
30
30
|
} from "convex/server";
|
|
31
31
|
import type { DataModel } from "./dataModel.js";
|
|
32
32
|
|
|
33
|
+
/**
|
|
34
|
+
* Typesafe environment variables.
|
|
35
|
+
*
|
|
36
|
+
* This includes platform-provided env vars and any variables declared in
|
|
37
|
+
* `convex.config.ts`.
|
|
38
|
+
*/
|
|
39
|
+
type Env = {
|
|
40
|
+
readonly CONVEX_CLOUD_URL: string;
|
|
41
|
+
readonly CONVEX_SITE_URL: string;
|
|
42
|
+
};
|
|
43
|
+
|
|
33
44
|
/**
|
|
34
45
|
* Define a query in this Convex app's public API.
|
|
35
46
|
*
|
|
@@ -106,6 +117,8 @@ export const internalAction: ActionBuilder<DataModel, "internal"> =
|
|
|
106
117
|
* @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
|
|
107
118
|
*/
|
|
108
119
|
export const httpAction: HttpActionBuilder = httpActionGeneric;
|
|
120
|
+
export const env: Env = (globalThis as unknown as { process: { env: Env } })
|
|
121
|
+
.process.env;
|
|
109
122
|
|
|
110
123
|
/**
|
|
111
124
|
* A set of services for use within Convex query functions.
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ConvexError, v } from "convex/values";
|
|
2
|
+
import { api } from "./_generated/api";
|
|
2
3
|
import type { Doc } from "./_generated/dataModel";
|
|
3
4
|
import type { MutationCtx } from "./_generated/server";
|
|
4
5
|
import { mutation } from "./_generated/server";
|
|
@@ -7,16 +8,16 @@ import { assignResult, experimentStatus, exposureResult, variant } from "./valid
|
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* Reject a malformed variant set before any write: at least one variant, every
|
|
10
|
-
* weight a positive finite number, and no duplicate variant keys.
|
|
11
|
-
*
|
|
12
|
-
* assignment ambiguous.
|
|
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
13
|
*
|
|
14
|
-
* @throws `ConvexError({ code: "INVALID_VARIANTS" })`
|
|
14
|
+
* @throws `ConvexError({ code: "INVALID_VARIANTS", reason })`
|
|
15
15
|
*/
|
|
16
16
|
function validateVariants(variants: readonly Variant[]): void {
|
|
17
17
|
if (variants.length === 0) {
|
|
18
18
|
throw new ConvexError({
|
|
19
19
|
code: "INVALID_VARIANTS",
|
|
20
|
+
reason: "empty",
|
|
20
21
|
message: "an experiment needs at least one variant",
|
|
21
22
|
});
|
|
22
23
|
}
|
|
@@ -25,12 +26,16 @@ function validateVariants(variants: readonly Variant[]): void {
|
|
|
25
26
|
if (!(candidate.weight > 0 && isFinite(candidate.weight))) {
|
|
26
27
|
throw new ConvexError({
|
|
27
28
|
code: "INVALID_VARIANTS",
|
|
29
|
+
reason: "non_positive_weight",
|
|
30
|
+
key: candidate.key,
|
|
28
31
|
message: `variant "${candidate.key}" weight must be a positive finite number`,
|
|
29
32
|
});
|
|
30
33
|
}
|
|
31
34
|
if (seen.has(candidate.key)) {
|
|
32
35
|
throw new ConvexError({
|
|
33
36
|
code: "INVALID_VARIANTS",
|
|
37
|
+
reason: "duplicate_key",
|
|
38
|
+
key: candidate.key,
|
|
34
39
|
message: `duplicate variant key "${candidate.key}"`,
|
|
35
40
|
});
|
|
36
41
|
}
|
|
@@ -38,10 +43,55 @@ function validateVariants(variants: readonly Variant[]): void {
|
|
|
38
43
|
}
|
|
39
44
|
}
|
|
40
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("variantTallies", row._id, {
|
|
83
|
+
assigned: row.assigned + assigned,
|
|
84
|
+
subjects: row.subjects + subjects,
|
|
85
|
+
exposures: row.exposures + exposures,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
41
90
|
/**
|
|
42
91
|
* Return the subject's sticky assignment, persisting a fresh deterministic pick on
|
|
43
|
-
* first sight
|
|
44
|
-
* share one enrollment path. Time is
|
|
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.
|
|
45
95
|
*/
|
|
46
96
|
async function ensureAssignment(
|
|
47
97
|
ctx: MutationCtx,
|
|
@@ -61,7 +111,7 @@ async function ensureAssignment(
|
|
|
61
111
|
if (existing !== null) {
|
|
62
112
|
return { variant: existing.variant, isNew: false };
|
|
63
113
|
}
|
|
64
|
-
const variantKey = pickVariant(experiment.variants, experiment
|
|
114
|
+
const variantKey = pickVariant(experiment.variants, hashSalt(experiment), subjectRef);
|
|
65
115
|
await ctx.db.insert("assignments", {
|
|
66
116
|
scope: experiment.scope,
|
|
67
117
|
experimentKey: experiment.key,
|
|
@@ -69,17 +119,29 @@ async function ensureAssignment(
|
|
|
69
119
|
variant: variantKey,
|
|
70
120
|
assignedAt: now,
|
|
71
121
|
});
|
|
122
|
+
await bumpTally(ctx, experiment.scope, experiment.key, variantKey, { assigned: 1 });
|
|
72
123
|
return { variant: variantKey, isNew: true };
|
|
73
124
|
}
|
|
74
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
|
+
|
|
75
131
|
/**
|
|
76
132
|
* Create or update an experiment definition, keyed by `(scope, key)`. Returns
|
|
77
|
-
* `{ created: true }` on insert, `{ created: false }` on update.
|
|
78
|
-
*
|
|
79
|
-
* status) changes. Time is server-sourced.
|
|
133
|
+
* `{ created: true }` on insert, `{ created: false }` on update. Time is
|
|
134
|
+
* server-sourced.
|
|
80
135
|
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
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.
|
|
83
145
|
*/
|
|
84
146
|
export const define = mutation({
|
|
85
147
|
args: {
|
|
@@ -109,7 +171,22 @@ export const define = mutation({
|
|
|
109
171
|
});
|
|
110
172
|
return { created: true };
|
|
111
173
|
}
|
|
112
|
-
|
|
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("experiments", existing._id, {
|
|
113
190
|
status: args.status,
|
|
114
191
|
variants: args.variants,
|
|
115
192
|
salt: args.salt,
|
|
@@ -137,7 +214,7 @@ export const setStatus = mutation({
|
|
|
137
214
|
if (existing === null) {
|
|
138
215
|
return false;
|
|
139
216
|
}
|
|
140
|
-
await ctx.db.patch(existing._id, { status: args.status });
|
|
217
|
+
await ctx.db.patch("experiments", existing._id, { status: args.status });
|
|
141
218
|
return true;
|
|
142
219
|
},
|
|
143
220
|
});
|
|
@@ -146,9 +223,7 @@ export const setStatus = mutation({
|
|
|
146
223
|
* Enroll `subjectRef` and return the sticky variant. `{ variant: null }` when the
|
|
147
224
|
* experiment is absent or not `running` (the host treats it as control). When
|
|
148
225
|
* `running`, the first call deterministically picks and persists a variant
|
|
149
|
-
* (`isNew: true`); later calls replay it (`isNew: false`).
|
|
150
|
-
* function of `(salt, subjectRef)` — see {@link pickVariant} — so it is sticky
|
|
151
|
-
* even before persistence. Time is server-sourced.
|
|
226
|
+
* (`isNew: true`); later calls replay it (`isNew: false`). Time is server-sourced.
|
|
152
227
|
*/
|
|
153
228
|
export const assign = mutation({
|
|
154
229
|
args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
|
|
@@ -168,11 +243,10 @@ export const assign = mutation({
|
|
|
168
243
|
});
|
|
169
244
|
|
|
170
245
|
/**
|
|
171
|
-
* Record that `subjectRef` was exposed
|
|
172
|
-
*
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
* unique subjects. `{ variant: null }` when not enrolled. Time is server-sourced.
|
|
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.
|
|
176
250
|
*/
|
|
177
251
|
export const logExposure = mutation({
|
|
178
252
|
args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
|
|
@@ -213,12 +287,134 @@ export const logExposure = mutation({
|
|
|
213
287
|
lastExposedAt: now,
|
|
214
288
|
count: 1,
|
|
215
289
|
});
|
|
290
|
+
await bumpTally(ctx, args.scope, args.key, variantKey, {
|
|
291
|
+
subjects: 1,
|
|
292
|
+
exposures: 1,
|
|
293
|
+
});
|
|
216
294
|
} else {
|
|
217
|
-
await ctx.db.patch(existing._id, {
|
|
295
|
+
await ctx.db.patch("exposures", existing._id, {
|
|
218
296
|
lastExposedAt: now,
|
|
219
297
|
count: existing.count + 1,
|
|
220
298
|
});
|
|
299
|
+
await bumpTally(ctx, args.scope, args.key, variantKey, { exposures: 1 });
|
|
221
300
|
}
|
|
222
301
|
return { variant: variantKey };
|
|
223
302
|
},
|
|
224
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("assignments", 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("exposures", 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
|
+
if (!Number.isFinite(args.batch) || !Number.isInteger(args.batch) || args.batch < 1 || args.batch > 500) {
|
|
365
|
+
throw new ConvexError({
|
|
366
|
+
code: "INVALID_BATCH",
|
|
367
|
+
message: "batch must be an integer between 1 and 500",
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
let removed = 0;
|
|
371
|
+
const assignments = await ctx.db
|
|
372
|
+
.query("assignments")
|
|
373
|
+
.withIndex("by_scope_experiment_subject", (q) =>
|
|
374
|
+
q.eq("scope", args.scope).eq("experimentKey", args.key),
|
|
375
|
+
)
|
|
376
|
+
.take(args.batch);
|
|
377
|
+
for (const row of assignments) {
|
|
378
|
+
await ctx.db.delete("assignments", row._id);
|
|
379
|
+
removed++;
|
|
380
|
+
}
|
|
381
|
+
const exposures = await ctx.db
|
|
382
|
+
.query("exposures")
|
|
383
|
+
.withIndex("by_scope_experiment", (q) =>
|
|
384
|
+
q.eq("scope", args.scope).eq("experimentKey", args.key),
|
|
385
|
+
)
|
|
386
|
+
.take(args.batch);
|
|
387
|
+
for (const row of exposures) {
|
|
388
|
+
await ctx.db.delete("exposures", row._id);
|
|
389
|
+
removed++;
|
|
390
|
+
}
|
|
391
|
+
const tallies = await ctx.db
|
|
392
|
+
.query("variantTallies")
|
|
393
|
+
.withIndex("by_scope_experiment", (q) =>
|
|
394
|
+
q.eq("scope", args.scope).eq("experimentKey", args.key),
|
|
395
|
+
)
|
|
396
|
+
.take(args.batch);
|
|
397
|
+
for (const row of tallies) {
|
|
398
|
+
await ctx.db.delete("variantTallies", row._id);
|
|
399
|
+
removed++;
|
|
400
|
+
}
|
|
401
|
+
if (removed > 0) {
|
|
402
|
+
await ctx.scheduler.runAfter(0, api.mutations.deleteExperiment, {
|
|
403
|
+
scope: args.scope,
|
|
404
|
+
key: args.key,
|
|
405
|
+
batch: args.batch,
|
|
406
|
+
});
|
|
407
|
+
return removed;
|
|
408
|
+
}
|
|
409
|
+
const def = await ctx.db
|
|
410
|
+
.query("experiments")
|
|
411
|
+
.withIndex("by_scope_key", (q) =>
|
|
412
|
+
q.eq("scope", args.scope).eq("key", args.key),
|
|
413
|
+
)
|
|
414
|
+
.unique();
|
|
415
|
+
if (def !== null) {
|
|
416
|
+
await ctx.db.delete("experiments", def._id);
|
|
417
|
+
}
|
|
418
|
+
return removed;
|
|
419
|
+
},
|
|
420
|
+
});
|