Deterministic A/B testing for Convex: sticky weighted variant assignment, deduped exposure tracking and per-variant tallies, as a Convex component.
Docs for the installed version are in node_modules/@vllnt/convex-experiments/:
docs/API.md, llms.txt, CHANGELOG.md and the TypeScript src/. Read them
before writing code against this package.
- Use it when every subject (user, device, team) must get one variant of an experiment, and the same one on every later call.
- Use it when traffic is split by relative weights (
1:1,90:10, N-way) and you need per-variant counts of assigned subjects, exposed subjects and exposures. - Use it when a server render or first paint needs the subject's variant before
anything is written (
peek). - Do not use it when you need release control, gradual rollouts, targeting rules or kill-switches: use a feature-flag system.
- Do not use it when you need to store outcomes (conversions, revenue, retention): use your own tables or an analytics event store, joined on the assigned variant.
- Do not use it when you need significance tests or confidence intervals: use a
statistics tool on the counts that
resultsreturns.
pnpm add @vllnt/convex-experiments// convex/convex.config.ts
import experiments from "@vllnt/convex-experiments/convex.config";
import { defineApp } from "convex/server";
const app = defineApp();
app.use(experiments);
export default app;// convex/checkout.ts
import { Experiments } from "@vllnt/convex-experiments";
import { ConvexError, v } from "convex/values";
import { components } from "./_generated/api";
import { internalMutation, mutation } from "./_generated/server";
const experiments = new Experiments(components.experiments);
export const setup = internalMutation({
args: {},
returns: v.boolean(),
handler: async (ctx) => {
const { created } = await experiments.define(ctx, "checkout_button", {
variants: [
{ key: "control", weight: 1 },
{ key: "one_click", weight: 1 },
],
});
return created;
},
});
export const checkoutVariant = mutation({
args: {},
returns: v.union(v.string(), v.null()),
handler: async (ctx) => {
const user = await ctx.auth.getUserIdentity();
if (user === null) throw new ConvexError("not signed in");
const { variant } = await experiments.logExposure(
ctx,
"checkout_button",
user.tokenIdentifier,
);
return variant;
},
});Run npx convex dev once to generate components.experiments, then
npx convex run checkout:setup once. Re-running setup is not a no-op after
you stop the experiment: it sets the status back to running (see Limits and
gotchas). checkoutVariant enrolls the caller on first
call and returns the same variant afterwards. It returns null when the
experiment is absent, draft or stopped: render your control. The component
never reads auth; the host derives subjectRef (here the user's
tokenIdentifier).
Full reference: docs/API.md.
| Export | Import from | What it does |
|---|---|---|
Experiments |
@vllnt/convex-experiments |
Host client: new Experiments(components.experiments, { defaultScope, defaultStatus }) |
define(ctx, key, opts) |
Experiments method, mutation |
Create or update an experiment; returns { created } |
setStatus(ctx, key, status, scope?) |
Experiments method, mutation |
Set draft, running or stopped; returns false when absent |
assign(ctx, key, subjectRef, scope?) |
Experiments method, mutation |
Enroll a subject; returns { variant: null } or { variant, isNew } |
logExposure(ctx, key, subjectRef, scope?) |
Experiments method, mutation |
Enroll if needed and count one exposure; returns { variant } |
forgetSubject(ctx, key, subjectRef, scope?) |
Experiments method, mutation |
Delete one subject's assignment and exposure rows; returns boolean |
deleteExperiment(ctx, key, opts?) |
Experiments method, mutation |
Delete the experiment and all its rows in batches; returns the first pass's row count |
getExperiment(ctx, key, scope?) |
Experiments method, query |
The definition, or null |
listExperiments(ctx, opts?) |
Experiments method, query |
Every experiment in one scope, optionally filtered by status |
getAssignment(ctx, key, subjectRef, scope?) |
Experiments method, query |
The stored assignment { variant, assignedAt }, or null |
peek(ctx, key, subjectRef, scope?) |
Experiments method, query |
The subject's variant without writing; returns { variant } |
results(ctx, key, scope?) |
Experiments method, query |
One { variant, assigned, subjects, exposures, weight } row per defined variant |
ExperimentsComponent |
@vllnt/convex-experiments (type) |
Type of components.experiments |
ExperimentsOptions |
@vllnt/convex-experiments (type) |
{ defaultScope?, defaultStatus? } |
DefineOptions |
@vllnt/convex-experiments (type) |
{ scope?, salt?, status? } for define |
ExperimentDefinition |
@vllnt/convex-experiments (type) |
Result of getExperiment and listExperiments |
ExperimentStatus |
@vllnt/convex-experiments (type) |
"draft" | "running" | "stopped" |
Variant |
@vllnt/convex-experiments (type) |
{ key, weight } |
Assignment |
@vllnt/convex-experiments (type) |
Result of getAssignment |
AssignOutcome |
@vllnt/convex-experiments (type) |
Result of assign |
ExposureOutcome |
@vllnt/convex-experiments (type) |
Result of logExposure and peek |
VariantResult |
@vllnt/convex-experiments (type) |
One row of results |
useVariant |
@vllnt/convex-experiments/react |
React hook over your peek wrapper; string | null | undefined |
useAssignment |
@vllnt/convex-experiments/react |
React hook over your getAssignment wrapper; Assignment | null | undefined |
useExperimentResults |
@vllnt/convex-experiments/react |
React hook over your results wrapper; VariantResult[] | undefined |
default (component config) |
@vllnt/convex-experiments/convex.config |
Pass to app.use(...) |
register |
@vllnt/convex-experiments/test |
Mount the component in a convex-test instance |
ComponentApi |
@vllnt/convex-experiments/_generated/component |
Generated type of the mounted component |
Stop an experiment and read its counts. assigned and weight per variant are
enough to check for a sample-ratio mismatch (observed vs expected split):
// convex/admin.ts
import { Experiments } from "@vllnt/convex-experiments";
import { v } from "convex/values";
import { components } from "./_generated/api";
import { internalMutation, internalQuery } from "./_generated/server";
const experiments = new Experiments(components.experiments);
export const stop = internalMutation({
args: { key: v.string() },
returns: v.boolean(),
handler: (ctx, { key }) => experiments.setStatus(ctx, key, "stopped"),
});
export const counts = internalQuery({
args: { key: v.string() },
returns: v.array(
v.object({
variant: v.string(),
assigned: v.number(),
subjects: v.number(),
exposures: v.number(),
weight: v.number(),
}),
),
handler: (ctx, { key }) => experiments.results(ctx, key),
});Record an outcome in your own table, joined on the assigned variant:
// convex/schema.ts
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";
export default defineSchema({
conversions: defineTable({
experimentKey: v.string(),
variant: v.string(),
subjectRef: v.string(),
}).index("by_experiment_variant", ["experimentKey", "variant"]),
});// convex/conversions.ts
import { Experiments } from "@vllnt/convex-experiments";
import { ConvexError, v } from "convex/values";
import { components } from "./_generated/api";
import { mutation } from "./_generated/server";
const experiments = new Experiments(components.experiments);
export const recordPurchase = mutation({
args: {},
returns: v.null(),
handler: async (ctx) => {
const user = await ctx.auth.getUserIdentity();
if (user === null) throw new ConvexError("not signed in");
const assignment = await experiments.getAssignment(
ctx,
"checkout_button",
user.tokenIdentifier,
);
if (assignment !== null) {
await ctx.db.insert("conversions", {
experimentKey: "checkout_button",
variant: assignment.variant,
subjectRef: user.tokenIdentifier,
});
}
return null;
},
});Get a first paint without a flash of the control in React (useVariant returns
undefined while loading). The hooks take a query reference that you export
from your own convex/ folder:
// convex/experiments.ts
import { Experiments } from "@vllnt/convex-experiments";
import { ConvexError, v } from "convex/values";
import { components } from "./_generated/api";
import { query } from "./_generated/server";
const experiments = new Experiments(components.experiments);
export const variant = query({
args: { key: v.string(), subjectRef: v.string() },
returns: v.object({ variant: v.union(v.string(), v.null()) }),
handler: async (ctx, { key, subjectRef }) => {
const user = await ctx.auth.getUserIdentity();
if (user?.tokenIdentifier !== subjectRef)
throw new ConvexError("not allowed");
return experiments.peek(ctx, key, subjectRef);
},
});// src/CheckoutButton.tsx
import { useVariant } from "@vllnt/convex-experiments/react";
import { api } from "../convex/_generated/api";
export function CheckoutButton({ subjectRef }: { subjectRef: string }) {
const variant = useVariant(api.experiments.variant, {
key: "checkout_button",
subjectRef,
});
if (variant === undefined) return null;
return (
<button type="button">
{variant === "one_click" ? "Buy now" : "Checkout"}
</button>
);
}useVariant reads peek, which writes nothing. Call a logExposure mutation
(such as checkoutVariant above) when the variant is shown, to enroll and count.
Erase one user from every experiment in a scope, and delete a finished
experiment. forgetSubject works on one experiment, so loop over
listExperiments. deleteExperiment schedules its own follow-up batches:
// convex/cleanup.ts
import { Experiments } from "@vllnt/convex-experiments";
import { v } from "convex/values";
import { components } from "./_generated/api";
import { internalMutation } from "./_generated/server";
const experiments = new Experiments(components.experiments);
export const eraseUser = internalMutation({
args: { subjectRef: v.string() },
returns: v.number(),
handler: async (ctx, { subjectRef }) => {
let erased = 0;
for (const experiment of await experiments.listExperiments(ctx)) {
if (await experiments.forgetSubject(ctx, experiment.key, subjectRef)) {
erased++;
}
}
return erased;
},
});
export const deleteFinished = internalMutation({
args: { key: v.string() },
returns: v.number(),
handler: async (ctx, { key }) => {
await experiments.setStatus(ctx, key, "stopped");
return experiments.deleteExperiment(ctx, key, { batch: 200 });
},
});Mount the component twice, or split one mount by scope. Named mounts share no tables or scheduled work; scopes are namespaces inside one mount (folded into the hash, so one subject buckets independently per scope), not access control:
// convex/convex.config.ts
import experiments from "@vllnt/convex-experiments/convex.config";
import { defineApp } from "convex/server";
const app = defineApp();
app.use(experiments, { name: "webExperiments" });
app.use(experiments, { name: "gameExperiments" });
export default app;// convex/clients.ts
import { Experiments } from "@vllnt/convex-experiments";
import { components } from "./_generated/api";
export const web = new Experiments(components.webExperiments);
export const game = new Experiments(components.gameExperiments, {
defaultScope: "season_1",
defaultStatus: "draft",
});Invalid input throws a ConvexError whose data is { code, message } (plus
reason, and key where it applies, for INVALID_VARIANTS). Catch it in the
host with error instanceof ConvexError and read error.data.code.
| Code | Message | Cause | Fix |
|---|---|---|---|
INVALID_ARGUMENT |
scope must be non-empty (or key, subjectRef) |
A mutation got an empty scope, key or subjectRef string. Queries do not check this. |
Pass non-empty strings; check the client defaultScope is not "" |
INVALID_VARIANTS with reason: "empty" |
an experiment needs at least one variant |
define got variants: [] |
Pass at least one variant |
INVALID_ARGUMENT |
scope must be at most 512 UTF-16 code units (or key, salt, subjectRef) |
New data over the limit: define with a new scope or key, or a new or changed salt; assign or logExposure with a new subjectRef |
Keep identifiers within 512 UTF-16 code units (string.length; an emoji counts as 2) |
INVALID_VARIANTS with reason: "too_many" |
an experiment has at most 100 variants |
define got more than 100 variants in a new or changed set |
Pass at most 100 variants |
INVALID_VARIANTS with reason: "empty_key" |
variant keys must be non-empty |
A variant has key: "" |
Give every variant a non-empty key |
INVALID_VARIANTS with reason: "key_too_long" |
variant keys must be at most 512 UTF-16 code units |
A variant key is over 512 UTF-16 code units in a new or changed set | Shorten the variant key to at most 512 |
INVALID_VARIANTS with reason: "non_positive_weight" |
variant "<key>" weight must be a positive finite number |
A weight is 0, negative, NaN or Infinity |
Use positive finite weights (fractions are allowed) |
INVALID_VARIANTS with reason: "duplicate_key" |
duplicate variant key "<key>" |
Two variants share a key | Make variant keys unique |
INVALID_VARIANTS with reason: "total_too_large" |
the sum of the variant weights must be a finite number |
The weights are each finite but add up to Infinity (for example two weights of 1e308) |
Use smaller weights; only their ratios matter |
INVALID_BATCH |
batch must be an integer between 1 and 500 |
deleteExperiment got a batch that is not an integer in 1..500 |
Omit batch (default 200) or pass an integer in 1..500 |
EXPERIMENT_DELETING |
a deleteExperiment for this key is still running; define it again once getExperiment returns null |
define was called while a multi-pass deleteExperiment for the same key had passes left (or its passes stopped for good, for example a pass kept failing) |
Wait until getExperiment returns null; if it never does, call deleteExperiment again to finish the delete; or use a new key |
EXPERIMENT_LOCKED |
variants and salt are immutable once subjects are assigned; define a new experiment key to re-randomize |
define changed variants (keys, weights or order) or salt while the experiment has at least one assignment |
Define a new experiment key; status-only changes are always allowed |
Error (no code) |
pickVariant requires at least one variant |
Internal guard. Not reachable through the public API: define rejects an empty variant set first |
None needed |
Arguments of the wrong type (for example a string weight) are rejected by
Convex argument validation before the component runs. The component throws no
other errors of its own: absent experiments and wrong scopes return null,
false, 0, { variant: null } or [] (see below).
- Only
runningexperiments enroll.assign,logExposureandpeekreturn{ variant: null }with no error when the experiment is absent,draftorstopped, and also for a misspelled key or a wrong scope. definestarts the experiment asrunningunless you passstatus: "draft"or construct the client withdefaultStatus: "draft".- Re-running
definewithoutstatusresets the status: the client sendsstatus: opts.status ?? defaultStatusand the update writes it, so astoppedexperiment starts enrolling again. Passstatusexplicitly when you re-rundefine, and usesetStatusfor lifecycle changes. - After
stopped,getAssignmentstill returns stored assignments, whileassign,logExposureandpeekreturn{ variant: null }. variants(keys, weights and their order) andsaltcannot change once any subject in that(scope, key)has an assignment (EXPERIMENT_LOCKED). Re-defining with identical input writes nothing and returns{ created: false }.- The variant is computed from
scope,salt(default: the experiment key),subjectRefand the ordered variants and weights, with a 32-bit FNV-1a hash over the UTF-16 code units (charCodeAt) of"<scope>:<salt>:<subjectRef>", not its UTF-8 bytes, followed by a 32-bit finalizer (murmur3fmix32), so similar or sequential refs such asu1,u2still split by the weights. It is deterministic bucketing, not randomness or a secret: anyone who knows those inputs can compute a subject's variant. - Every
logExposurecall adds 1 toexposures; there is no idempotency key, so a retried call counts again.subjectscounts each subject once.assignalone adds toassigned, not tosubjectsorexposures. forgetSubjectis not an opt-out: a laterassignorlogExposureenrolls the subject again, into the same variant while the definition is unchanged.deleteExperimentdeletes up tobatchrows per table per pass (default 200, integer 1..500) and reschedules itself until done. It returns only the first pass's count and does not count the definition row. The definition stays until the last pass, so arunningexperiment keeps enrolling meanwhile: stop it first. While passes are left,definefor that key throwsEXPERIMENT_DELETINGinstead of updating a definition the next pass would delete. Each scheduled pass is pinned to the definition it started on, so a pass left over from a seconddeleteExperimentcall never deletes a newer definition of the key. If the passes stop for good, the key stays marked: calldeleteExperimentagain to finish.listExperimentsandresultsare not paginated.listExperimentsreads every experiment in the scope; calls that omitscopeuse the clientdefaultScope("global"), never all scopes. Rows come back in creation order within the scope (oldest first), not sorted by key.resultsreturns[]for an absent experiment and one zeroed row per defined variant before anyone enrolls.- Only mutations reject empty
scope,keyandsubjectRef(INVALID_ARGUMENT). Queries do not validate them:peek(ctx, key, "")on arunningexperiment returns a real variant, the deterministic pick for the empty string. - New data is capped:
scope,key,salt,subjectRefand each variant key are at most 512 UTF-16 code units, and an experiment has at most 100 variants. The length is JavaScriptstring.length, not characters and not UTF-8 bytes: an emoji counts as 2, so 256 emoji pass and 256 emoji plus one letter do not. Exactly 512 passes; 513 throwsINVALID_ARGUMENT(orINVALID_VARIANTSwithreason: "key_too_long"or"too_many"). The caps apply todefine(a new experiment, or a changedvariantsorsalt) and toassignandlogExposurefor a subject with no stored assignment. Queries (includingpeek) do not check length. - Data stored by 0.1.0 with a longer value stays readable.
setStatus,forgetSubject,deleteExperiment, adefinethat changes onlystatus, andassignorlogExposurefor a subject already stored keep working. Adefinethat changesvariantsorsaltis checked as new data, even if it keeps the old over-long value. For an existing experiment with a longer key or more than 100 variants, define a new shorter key. - Scopes are namespaces, not authorization. The component reads no auth.
- Timestamps (
createdAt,assignedAt) are server time in ms; no method accepts a caller timestamp. - Option types are
{ scope?: string }, not{ scope?: string | undefined }. UnderexactOptionalPropertyTypes, omit a key instead of passingundefined, for example...(scope === undefined ? {} : { scope }).
- Peer dependency:
convex@^1.45.0. This repository develops and tests against convex 1.51. react >=18is an optional peer dependency, needed only for@vllnt/convex-experiments/react(which also importsconvex/react). A backend-only app needs no React.- Node.js
>=20(engines.node), matching the oldest supportedconvexpeer (1.45). Theconvexversion you install may need a newer Node: 1.51 needs>=22. Check withnpm view convex@1.51.0 engines. ES modules only. @vllnt/convex-experiments/testships as TypeScript source (src/test.ts) and needsconvex-testand Vite'simport.meta.glob, for example throughvitest, withvite/clienttypes.convex-test0.0.72 and later requireconvex ^1.46.0, so onconvex1.45 useconvex-test0.0.71 or older. Check withnpm view convex-test@0.0.72 peerDependencies.
Mount the component in your own convex-test suite with register. This
test uses the Quick start's convex/checkout.ts and runs in Vitest's
edge-runtime environment (@edge-runtime/vm):
// convex/checkout.test.ts
/// <reference types="vite/client" />
import { register } from "@vllnt/convex-experiments/test";
import { convexTest } from "convex-test";
import { expect, test } from "vitest";
import { api, internal } from "./_generated/api";
import schema from "./schema";
test("a signed-in user keeps one variant", async () => {
const t = convexTest(schema, import.meta.glob("./**/*.ts"));
register(t);
await t.mutation(internal.checkout.setup, {});
const user = t.withIdentity({ tokenIdentifier: "user-1" });
const first = await user.mutation(api.checkout.checkoutVariant, {});
const again = await user.mutation(api.checkout.checkoutVariant, {});
expect(first).not.toBeNull();
expect(again).toBe(first);
});register(t, name) takes the mount name when you used
app.use(experiments, { name }); the default is "experiments".
This repository's own tests (pnpm test, pnpm test:coverage with 100%
coverage enforced) use the simulated convex-test backend, not a real Convex
deployment; they do not prove production concurrency or scheduler delivery.
- The component does not authenticate. The host must authorize every call and
derive
subjectRefandscopeitself, or check a client-sentsubjectRefagainst the caller's identity as in the React example above. - Its tables are reachable only through the component's functions;
subjectRef, variant keys andscopeare opaque strings. - A variant is not a secret or an entitlement: it can be computed from the experiment inputs (see Limits and gotchas).
forgetSubjectdeletes a subject's assignment and exposure rows in one experiment and lowers the tallies, for right-to-erasure requests.
Report vulnerabilities as described in SECURITY.md.
None. No other @vllnt package is used with this one in code (no dependency, shared test or example).
See CONTRIBUTING.md.
- Docs and changelog: oss.vllnt.com/packages/convex-experiments · release feed
- All @vllnt packages: oss.vllnt.com · search packages and docs on index.vllnt.com
- Source and issues: GitHub · issues · npm
- Questions and updates: Discord · X @bntvllnt
- Company and author: vllnt.com · bntvllnt.com · GitHub @bntvllnt · LinkedIn
- Sponsor: GitHub Sponsors
MIT. See LICENSE.
Part of vllnt open source · Package page · vllnt.com · Built by bntvllnt