@vllnt/convex-experiments 0.1.0-canary.207ab91
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/LICENSE +21 -0
- package/README.md +132 -0
- package/dist/client/index.d.ts +117 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +105 -0
- package/dist/client/index.js.map +1 -0
- package/dist/client/types.d.ts +70 -0
- package/dist/client/types.d.ts.map +1 -0
- package/dist/client/types.js +3 -0
- package/dist/client/types.js.map +1 -0
- package/dist/component/_generated/api.d.ts +38 -0
- package/dist/component/_generated/api.d.ts.map +1 -0
- package/dist/component/_generated/api.js +31 -0
- package/dist/component/_generated/api.js.map +1 -0
- package/dist/component/_generated/component.d.ts +93 -0
- package/dist/component/_generated/component.d.ts.map +1 -0
- package/dist/component/_generated/component.js +11 -0
- package/dist/component/_generated/component.js.map +1 -0
- package/dist/component/_generated/dataModel.d.ts +46 -0
- package/dist/component/_generated/dataModel.d.ts.map +1 -0
- package/dist/component/_generated/dataModel.js +11 -0
- package/dist/component/_generated/dataModel.js.map +1 -0
- package/dist/component/_generated/server.d.ts +121 -0
- package/dist/component/_generated/server.d.ts.map +1 -0
- package/dist/component/_generated/server.js +78 -0
- package/dist/component/_generated/server.js.map +1 -0
- package/dist/component/convex.config.d.ts +3 -0
- package/dist/component/convex.config.d.ts.map +1 -0
- package/dist/component/convex.config.js +7 -0
- package/dist/component/convex.config.js.map +1 -0
- package/dist/component/mutations.d.ts +67 -0
- package/dist/component/mutations.d.ts.map +1 -0
- package/dist/component/mutations.js +196 -0
- package/dist/component/mutations.js.map +1 -0
- package/dist/component/queries.d.ts +39 -0
- package/dist/component/queries.d.ts.map +1 -0
- package/dist/component/queries.js +72 -0
- package/dist/component/queries.js.map +1 -0
- package/dist/component/schema.d.ts +77 -0
- package/dist/component/schema.d.ts.map +1 -0
- package/dist/component/schema.js +49 -0
- package/dist/component/schema.js.map +1 -0
- package/dist/component/validators.d.ts +96 -0
- package/dist/component/validators.d.ts.map +1 -0
- package/dist/component/validators.js +38 -0
- package/dist/component/validators.js.map +1 -0
- package/dist/shared.d.ts +30 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +50 -0
- package/dist/shared.js.map +1 -0
- package/package.json +98 -0
- package/src/client/index.ts +249 -0
- package/src/client/types.ts +73 -0
- package/src/component/_generated/api.ts +54 -0
- package/src/component/_generated/component.ts +92 -0
- package/src/component/_generated/dataModel.ts +60 -0
- package/src/component/_generated/server.ts +156 -0
- package/src/component/convex.config.ts +9 -0
- package/src/component/mutations.ts +224 -0
- package/src/component/queries.ts +84 -0
- package/src/component/schema.ts +55 -0
- package/src/component/validators.ts +54 -0
- package/src/shared.ts +66 -0
- package/src/test.ts +12 -0
- package/src/unit.test.ts +84 -0
|
@@ -0,0 +1,224 @@
|
|
|
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";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 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.
|
|
13
|
+
*
|
|
14
|
+
* @throws `ConvexError({ code: "INVALID_VARIANTS" })`
|
|
15
|
+
*/
|
|
16
|
+
function validateVariants(variants: readonly Variant[]): void {
|
|
17
|
+
if (variants.length === 0) {
|
|
18
|
+
throw new ConvexError({
|
|
19
|
+
code: "INVALID_VARIANTS",
|
|
20
|
+
message: "an experiment needs at least one variant",
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
const seen = new Set<string>();
|
|
24
|
+
for (const candidate of variants) {
|
|
25
|
+
if (!(candidate.weight > 0 && isFinite(candidate.weight))) {
|
|
26
|
+
throw new ConvexError({
|
|
27
|
+
code: "INVALID_VARIANTS",
|
|
28
|
+
message: `variant "${candidate.key}" weight must be a positive finite number`,
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
if (seen.has(candidate.key)) {
|
|
32
|
+
throw new ConvexError({
|
|
33
|
+
code: "INVALID_VARIANTS",
|
|
34
|
+
message: `duplicate variant key "${candidate.key}"`,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
seen.add(candidate.key);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* 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.
|
|
45
|
+
*/
|
|
46
|
+
async function ensureAssignment(
|
|
47
|
+
ctx: MutationCtx,
|
|
48
|
+
experiment: Doc<"experiments">,
|
|
49
|
+
subjectRef: string,
|
|
50
|
+
now: number,
|
|
51
|
+
): Promise<{ variant: string; isNew: boolean }> {
|
|
52
|
+
const existing = await ctx.db
|
|
53
|
+
.query("assignments")
|
|
54
|
+
.withIndex("by_scope_experiment_subject", (q) =>
|
|
55
|
+
q
|
|
56
|
+
.eq("scope", experiment.scope)
|
|
57
|
+
.eq("experimentKey", experiment.key)
|
|
58
|
+
.eq("subjectRef", subjectRef),
|
|
59
|
+
)
|
|
60
|
+
.unique();
|
|
61
|
+
if (existing !== null) {
|
|
62
|
+
return { variant: existing.variant, isNew: false };
|
|
63
|
+
}
|
|
64
|
+
const variantKey = pickVariant(experiment.variants, experiment.salt, subjectRef);
|
|
65
|
+
await ctx.db.insert("assignments", {
|
|
66
|
+
scope: experiment.scope,
|
|
67
|
+
experimentKey: experiment.key,
|
|
68
|
+
subjectRef,
|
|
69
|
+
variant: variantKey,
|
|
70
|
+
assignedAt: now,
|
|
71
|
+
});
|
|
72
|
+
return { variant: variantKey, isNew: true };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* 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.
|
|
80
|
+
*
|
|
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.
|
|
83
|
+
*/
|
|
84
|
+
export const define = mutation({
|
|
85
|
+
args: {
|
|
86
|
+
scope: v.string(),
|
|
87
|
+
key: v.string(),
|
|
88
|
+
variants: v.array(variant),
|
|
89
|
+
salt: v.string(),
|
|
90
|
+
status: experimentStatus,
|
|
91
|
+
},
|
|
92
|
+
returns: v.object({ created: v.boolean() }),
|
|
93
|
+
handler: async (ctx, args) => {
|
|
94
|
+
validateVariants(args.variants);
|
|
95
|
+
const existing = await ctx.db
|
|
96
|
+
.query("experiments")
|
|
97
|
+
.withIndex("by_scope_key", (q) =>
|
|
98
|
+
q.eq("scope", args.scope).eq("key", args.key),
|
|
99
|
+
)
|
|
100
|
+
.unique();
|
|
101
|
+
if (existing === null) {
|
|
102
|
+
await ctx.db.insert("experiments", {
|
|
103
|
+
key: args.key,
|
|
104
|
+
scope: args.scope,
|
|
105
|
+
status: args.status,
|
|
106
|
+
variants: args.variants,
|
|
107
|
+
salt: args.salt,
|
|
108
|
+
createdAt: Date.now(),
|
|
109
|
+
});
|
|
110
|
+
return { created: true };
|
|
111
|
+
}
|
|
112
|
+
await ctx.db.patch(existing._id, {
|
|
113
|
+
status: args.status,
|
|
114
|
+
variants: args.variants,
|
|
115
|
+
salt: args.salt,
|
|
116
|
+
});
|
|
117
|
+
return { created: false };
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Move an experiment to a new lifecycle `status`. Returns `false` when no
|
|
123
|
+
* experiment exists for `(scope, key)`, `true` once patched. Stopping an
|
|
124
|
+
* experiment freezes enrollment (`assign` returns `{ variant: null }`) while
|
|
125
|
+
* leaving recorded assignments and exposures intact.
|
|
126
|
+
*/
|
|
127
|
+
export const setStatus = mutation({
|
|
128
|
+
args: { scope: v.string(), key: v.string(), status: experimentStatus },
|
|
129
|
+
returns: v.boolean(),
|
|
130
|
+
handler: async (ctx, args) => {
|
|
131
|
+
const existing = await ctx.db
|
|
132
|
+
.query("experiments")
|
|
133
|
+
.withIndex("by_scope_key", (q) =>
|
|
134
|
+
q.eq("scope", args.scope).eq("key", args.key),
|
|
135
|
+
)
|
|
136
|
+
.unique();
|
|
137
|
+
if (existing === null) {
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
await ctx.db.patch(existing._id, { status: args.status });
|
|
141
|
+
return true;
|
|
142
|
+
},
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Enroll `subjectRef` and return the sticky variant. `{ variant: null }` when the
|
|
147
|
+
* experiment is absent or not `running` (the host treats it as control). When
|
|
148
|
+
* `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.
|
|
152
|
+
*/
|
|
153
|
+
export const assign = mutation({
|
|
154
|
+
args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
|
|
155
|
+
returns: assignResult,
|
|
156
|
+
handler: async (ctx, args) => {
|
|
157
|
+
const experiment = 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 (experiment === null || experiment.status !== "running") {
|
|
164
|
+
return { variant: null };
|
|
165
|
+
}
|
|
166
|
+
return ensureAssignment(ctx, experiment, args.subjectRef, Date.now());
|
|
167
|
+
},
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
/**
|
|
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.
|
|
176
|
+
*/
|
|
177
|
+
export const logExposure = mutation({
|
|
178
|
+
args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
|
|
179
|
+
returns: exposureResult,
|
|
180
|
+
handler: async (ctx, args) => {
|
|
181
|
+
const experiment = await ctx.db
|
|
182
|
+
.query("experiments")
|
|
183
|
+
.withIndex("by_scope_key", (q) =>
|
|
184
|
+
q.eq("scope", args.scope).eq("key", args.key),
|
|
185
|
+
)
|
|
186
|
+
.unique();
|
|
187
|
+
if (experiment === null || experiment.status !== "running") {
|
|
188
|
+
return { variant: null };
|
|
189
|
+
}
|
|
190
|
+
const now = Date.now();
|
|
191
|
+
const { variant: variantKey } = await ensureAssignment(
|
|
192
|
+
ctx,
|
|
193
|
+
experiment,
|
|
194
|
+
args.subjectRef,
|
|
195
|
+
now,
|
|
196
|
+
);
|
|
197
|
+
const existing = await ctx.db
|
|
198
|
+
.query("exposures")
|
|
199
|
+
.withIndex("by_scope_experiment_subject", (q) =>
|
|
200
|
+
q
|
|
201
|
+
.eq("scope", args.scope)
|
|
202
|
+
.eq("experimentKey", args.key)
|
|
203
|
+
.eq("subjectRef", args.subjectRef),
|
|
204
|
+
)
|
|
205
|
+
.unique();
|
|
206
|
+
if (existing === null) {
|
|
207
|
+
await ctx.db.insert("exposures", {
|
|
208
|
+
scope: args.scope,
|
|
209
|
+
experimentKey: args.key,
|
|
210
|
+
subjectRef: args.subjectRef,
|
|
211
|
+
variant: variantKey,
|
|
212
|
+
firstExposedAt: now,
|
|
213
|
+
lastExposedAt: now,
|
|
214
|
+
count: 1,
|
|
215
|
+
});
|
|
216
|
+
} else {
|
|
217
|
+
await ctx.db.patch(existing._id, {
|
|
218
|
+
lastExposedAt: now,
|
|
219
|
+
count: existing.count + 1,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
return { variant: variantKey };
|
|
223
|
+
},
|
|
224
|
+
});
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { v } from "convex/values";
|
|
2
|
+
import { query } from "./_generated/server";
|
|
3
|
+
import {
|
|
4
|
+
assignmentProjection,
|
|
5
|
+
experimentDef,
|
|
6
|
+
variantResult,
|
|
7
|
+
} from "./validators";
|
|
8
|
+
|
|
9
|
+
/** The experiment definition for `(scope, key)`, or `null` if none exists. */
|
|
10
|
+
export const getExperiment = query({
|
|
11
|
+
args: { scope: v.string(), key: v.string() },
|
|
12
|
+
returns: v.union(v.null(), experimentDef),
|
|
13
|
+
handler: async (ctx, args) => {
|
|
14
|
+
const row = await ctx.db
|
|
15
|
+
.query("experiments")
|
|
16
|
+
.withIndex("by_scope_key", (q) =>
|
|
17
|
+
q.eq("scope", args.scope).eq("key", args.key),
|
|
18
|
+
)
|
|
19
|
+
.unique();
|
|
20
|
+
if (row === null) {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
return {
|
|
24
|
+
key: row.key,
|
|
25
|
+
scope: row.scope,
|
|
26
|
+
status: row.status,
|
|
27
|
+
variants: row.variants,
|
|
28
|
+
salt: row.salt,
|
|
29
|
+
createdAt: row.createdAt,
|
|
30
|
+
};
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
/** A subject's sticky assignment for an experiment, or `null` if not enrolled. */
|
|
35
|
+
export const getAssignment = query({
|
|
36
|
+
args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
|
|
37
|
+
returns: v.union(v.null(), assignmentProjection),
|
|
38
|
+
handler: async (ctx, args) => {
|
|
39
|
+
const row = await ctx.db
|
|
40
|
+
.query("assignments")
|
|
41
|
+
.withIndex("by_scope_experiment_subject", (q) =>
|
|
42
|
+
q
|
|
43
|
+
.eq("scope", args.scope)
|
|
44
|
+
.eq("experimentKey", args.key)
|
|
45
|
+
.eq("subjectRef", args.subjectRef),
|
|
46
|
+
)
|
|
47
|
+
.unique();
|
|
48
|
+
if (row === null) {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
return { variant: row.variant, assignedAt: row.assignedAt };
|
|
52
|
+
},
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
/**
|
|
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.
|
|
60
|
+
*/
|
|
61
|
+
export const results = query({
|
|
62
|
+
args: { scope: v.string(), key: v.string() },
|
|
63
|
+
returns: v.array(variantResult),
|
|
64
|
+
handler: async (ctx, args) => {
|
|
65
|
+
const rows = await ctx.db
|
|
66
|
+
.query("exposures")
|
|
67
|
+
.withIndex("by_scope_experiment", (q) =>
|
|
68
|
+
q.eq("scope", args.scope).eq("experimentKey", args.key),
|
|
69
|
+
)
|
|
70
|
+
.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
|
+
}));
|
|
83
|
+
},
|
|
84
|
+
});
|
|
@@ -0,0 +1,55 @@
|
|
|
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
|
+
*/
|
|
14
|
+
export default defineSchema({
|
|
15
|
+
experiments: defineTable({
|
|
16
|
+
key: v.string(),
|
|
17
|
+
scope: v.string(),
|
|
18
|
+
status: v.union(
|
|
19
|
+
v.literal("draft"),
|
|
20
|
+
v.literal("running"),
|
|
21
|
+
v.literal("stopped"),
|
|
22
|
+
),
|
|
23
|
+
variants: v.array(variant),
|
|
24
|
+
salt: v.string(),
|
|
25
|
+
createdAt: v.number(),
|
|
26
|
+
}).index("by_scope_key", ["scope", "key"]),
|
|
27
|
+
|
|
28
|
+
assignments: defineTable({
|
|
29
|
+
scope: v.string(),
|
|
30
|
+
experimentKey: v.string(),
|
|
31
|
+
subjectRef: v.string(),
|
|
32
|
+
variant: v.string(),
|
|
33
|
+
assignedAt: v.number(),
|
|
34
|
+
}).index("by_scope_experiment_subject", [
|
|
35
|
+
"scope",
|
|
36
|
+
"experimentKey",
|
|
37
|
+
"subjectRef",
|
|
38
|
+
]),
|
|
39
|
+
|
|
40
|
+
exposures: defineTable({
|
|
41
|
+
scope: v.string(),
|
|
42
|
+
experimentKey: v.string(),
|
|
43
|
+
subjectRef: v.string(),
|
|
44
|
+
variant: v.string(),
|
|
45
|
+
firstExposedAt: v.number(),
|
|
46
|
+
lastExposedAt: v.number(),
|
|
47
|
+
count: v.number(),
|
|
48
|
+
})
|
|
49
|
+
.index("by_scope_experiment_subject", [
|
|
50
|
+
"scope",
|
|
51
|
+
"experimentKey",
|
|
52
|
+
"subjectRef",
|
|
53
|
+
])
|
|
54
|
+
.index("by_scope_experiment", ["scope", "experimentKey"]),
|
|
55
|
+
});
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { v } from "convex/values";
|
|
2
|
+
|
|
3
|
+
/** A weighted variant — an opaque variant key and its relative selection weight. */
|
|
4
|
+
export const variant = v.object({ key: v.string(), weight: v.number() });
|
|
5
|
+
|
|
6
|
+
/** Experiment lifecycle status. `running` is the only status that enrolls subjects. */
|
|
7
|
+
export const experimentStatus = v.union(
|
|
8
|
+
v.literal("draft"),
|
|
9
|
+
v.literal("running"),
|
|
10
|
+
v.literal("stopped"),
|
|
11
|
+
);
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Result of `assign`. `{ variant: null }` — the experiment is absent or not
|
|
15
|
+
* `running`, so the subject is not enrolled (the host treats this as control).
|
|
16
|
+
* `{ variant, isNew }` — the enrolled variant key, with `isNew` true only on the
|
|
17
|
+
* call that first persisted the assignment.
|
|
18
|
+
*/
|
|
19
|
+
export const assignResult = v.union(
|
|
20
|
+
v.object({ variant: v.null() }),
|
|
21
|
+
v.object({ variant: v.string(), isNew: v.boolean() }),
|
|
22
|
+
);
|
|
23
|
+
|
|
24
|
+
/** Result of `logExposure`: the enrolled variant, or `null` when not enrolled. */
|
|
25
|
+
export const exposureResult = v.union(
|
|
26
|
+
v.object({ variant: v.null() }),
|
|
27
|
+
v.object({ variant: v.string() }),
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
/** Projection of an experiment definition returned by `getExperiment`. */
|
|
31
|
+
export const experimentDef = v.object({
|
|
32
|
+
key: v.string(),
|
|
33
|
+
scope: v.string(),
|
|
34
|
+
status: experimentStatus,
|
|
35
|
+
variants: v.array(variant),
|
|
36
|
+
salt: v.string(),
|
|
37
|
+
createdAt: v.number(),
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
/** Projection of a subject's sticky assignment returned by `getAssignment`. */
|
|
41
|
+
export const assignmentProjection = v.object({
|
|
42
|
+
variant: v.string(),
|
|
43
|
+
assignedAt: v.number(),
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
/** Per-variant exposure tally returned by `results`. */
|
|
47
|
+
export const variantResult = v.object({
|
|
48
|
+
/** The variant key. */
|
|
49
|
+
variant: v.string(),
|
|
50
|
+
/** Distinct subjects exposed to this variant (the funnel denominator). */
|
|
51
|
+
subjects: v.number(),
|
|
52
|
+
/** Total exposure events recorded for this variant. */
|
|
53
|
+
exposures: v.number(),
|
|
54
|
+
});
|
package/src/shared.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/** Shared constants + pure deterministic assignment used by both `client/` and `component/`. */
|
|
2
|
+
|
|
3
|
+
export const COMPONENT_NAME = "experiments";
|
|
4
|
+
|
|
5
|
+
/** Default namespace when the host does not scope an experiment. */
|
|
6
|
+
export const DEFAULT_SCOPE = "global";
|
|
7
|
+
|
|
8
|
+
/** Lifecycle status the client applies to `define` when the caller omits one. */
|
|
9
|
+
export const DEFAULT_STATUS = "running";
|
|
10
|
+
|
|
11
|
+
/** A weighted variant: an opaque variant key and its relative selection weight. */
|
|
12
|
+
export interface Variant {
|
|
13
|
+
/** The host's opaque variant key (e.g. `"control"`, `"treatment"`). */
|
|
14
|
+
key: string;
|
|
15
|
+
/** Relative selection weight; the bucket width is `weight / sum(weights)`. */
|
|
16
|
+
weight: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* FNV-1a 32-bit hash of `input`, returned as an unsigned integer. Deterministic,
|
|
21
|
+
* synchronous, and dependency-free — the component runs in a V8 isolate, so a
|
|
22
|
+
* pure string hash (rather than async `crypto.subtle`) is what keeps variant
|
|
23
|
+
* assignment a plain function callable inside a mutation.
|
|
24
|
+
*/
|
|
25
|
+
export function fnv1a(input: string): number {
|
|
26
|
+
let hash = 0x811c9dc5;
|
|
27
|
+
for (let i = 0; i < input.length; i++) {
|
|
28
|
+
hash ^= input.charCodeAt(i);
|
|
29
|
+
hash = Math.imul(hash, 0x01000193);
|
|
30
|
+
}
|
|
31
|
+
return hash >>> 0;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Deterministically pick a variant for `subjectRef` from `variants`, weighted by
|
|
36
|
+
* each variant's `weight`. The same `(salt, subjectRef)` always maps to the same
|
|
37
|
+
* variant — sticky assignment with no storage — and the distribution matches the
|
|
38
|
+
* weights. `salt` lets a host re-randomize an experiment (a fresh re-run) without
|
|
39
|
+
* changing subject ids. Assumes a non-empty `variants` with positive weights; the
|
|
40
|
+
* caller validates that upstream.
|
|
41
|
+
*/
|
|
42
|
+
export function pickVariant(
|
|
43
|
+
variants: readonly Variant[],
|
|
44
|
+
salt: string,
|
|
45
|
+
subjectRef: string,
|
|
46
|
+
): string {
|
|
47
|
+
const lastVariant = variants[variants.length - 1];
|
|
48
|
+
if (lastVariant === undefined) {
|
|
49
|
+
throw new Error("pickVariant requires at least one variant");
|
|
50
|
+
}
|
|
51
|
+
let total = 0;
|
|
52
|
+
for (const variant of variants) {
|
|
53
|
+
total += variant.weight;
|
|
54
|
+
}
|
|
55
|
+
// Map the hash into [0, total): a point on the cumulative-weight line.
|
|
56
|
+
let target = (fnv1a(`${salt}:${subjectRef}`) / 0x100000000) * total;
|
|
57
|
+
// Walk every variant but the last, subtracting its bucket width.
|
|
58
|
+
for (const variant of variants.slice(0, -1)) {
|
|
59
|
+
target -= variant.weight;
|
|
60
|
+
if (target < 0) {
|
|
61
|
+
return variant.key;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
// The point fell in the final variant's bucket (also the single-variant case).
|
|
65
|
+
return lastVariant.key;
|
|
66
|
+
}
|
package/src/test.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { TestConvex } from "convex-test";
|
|
2
|
+
import schema from "./component/schema";
|
|
3
|
+
|
|
4
|
+
const modules = import.meta.glob("./component/**/*.ts");
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Register this component with a `convex-test` instance so consuming apps can test
|
|
8
|
+
* integration: `import { register } from "@vllnt/convex-experiments/test"`.
|
|
9
|
+
*/
|
|
10
|
+
export function register(t: TestConvex<typeof schema>, name = "experiments"): void {
|
|
11
|
+
t.registerComponent(name, schema, modules);
|
|
12
|
+
}
|
package/src/unit.test.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { describe, expect, test } from "vitest";
|
|
2
|
+
import { fnv1a, pickVariant, type Variant } from "./shared";
|
|
3
|
+
|
|
4
|
+
describe("fnv1a", () => {
|
|
5
|
+
test("is deterministic for the same input", () => {
|
|
6
|
+
expect(fnv1a("abc")).toBe(fnv1a("abc"));
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
test("differs for different inputs and returns an unsigned 32-bit int", () => {
|
|
10
|
+
const a = fnv1a("salt:user_1");
|
|
11
|
+
const b = fnv1a("salt:user_2");
|
|
12
|
+
expect(a).not.toBe(b);
|
|
13
|
+
expect(a).toBeGreaterThanOrEqual(0);
|
|
14
|
+
expect(a).toBeLessThan(0x100000000);
|
|
15
|
+
expect(Number.isInteger(a)).toBe(true);
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
describe("pickVariant", () => {
|
|
20
|
+
test("an empty variant set throws (guarded precondition)", () => {
|
|
21
|
+
expect(() => pickVariant([], "s", "u")).toThrow(/at least one variant/);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test("a single variant always wins (final-bucket path, no loop)", () => {
|
|
25
|
+
const variants: Variant[] = [{ key: "only", weight: 1 }];
|
|
26
|
+
for (let i = 0; i < 20; i++) {
|
|
27
|
+
expect(pickVariant(variants, "s", `u${i}`)).toBe("only");
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test("is sticky — same (salt, subject) always maps to the same variant", () => {
|
|
32
|
+
const variants: Variant[] = [
|
|
33
|
+
{ key: "a", weight: 1 },
|
|
34
|
+
{ key: "b", weight: 1 },
|
|
35
|
+
];
|
|
36
|
+
const first = pickVariant(variants, "exp", "user_42");
|
|
37
|
+
for (let i = 0; i < 10; i++) {
|
|
38
|
+
expect(pickVariant(variants, "exp", "user_42")).toBe(first);
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test("changing the salt can re-randomize a subject's bucket", () => {
|
|
43
|
+
const variants: Variant[] = [
|
|
44
|
+
{ key: "a", weight: 1 },
|
|
45
|
+
{ key: "b", weight: 1 },
|
|
46
|
+
];
|
|
47
|
+
// Across many subjects, the two salts disagree at least once.
|
|
48
|
+
let differs = false;
|
|
49
|
+
for (let i = 0; i < 50 && !differs; i++) {
|
|
50
|
+
differs =
|
|
51
|
+
pickVariant(variants, "salt_1", `u${i}`) !==
|
|
52
|
+
pickVariant(variants, "salt_2", `u${i}`);
|
|
53
|
+
}
|
|
54
|
+
expect(differs).toBe(true);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test("covers both the early-return and final-bucket branches across subjects", () => {
|
|
58
|
+
const variants: Variant[] = [
|
|
59
|
+
{ key: "a", weight: 1 },
|
|
60
|
+
{ key: "b", weight: 1 },
|
|
61
|
+
];
|
|
62
|
+
const seen = new Set<string>();
|
|
63
|
+
for (let i = 0; i < 200; i++) {
|
|
64
|
+
seen.add(pickVariant(variants, "spread", `subject_${i}`));
|
|
65
|
+
}
|
|
66
|
+
expect(seen).toEqual(new Set(["a", "b"]));
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test("respects weights — a dominant variant wins the vast majority", () => {
|
|
70
|
+
const variants: Variant[] = [
|
|
71
|
+
{ key: "rare", weight: 1 },
|
|
72
|
+
{ key: "common", weight: 99 },
|
|
73
|
+
];
|
|
74
|
+
let common = 0;
|
|
75
|
+
const n = 1000;
|
|
76
|
+
for (let i = 0; i < n; i++) {
|
|
77
|
+
if (pickVariant(variants, "w", `s_${i}`) === "common") {
|
|
78
|
+
common++;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
// ~99% expected; assert a wide, deterministic-safe band.
|
|
82
|
+
expect(common).toBeGreaterThan(n * 0.9);
|
|
83
|
+
});
|
|
84
|
+
});
|