@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,65 @@
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
+ /**
25
+ * Result of `logExposure` / `peek`: the enrolled variant, or `null` when the
26
+ * subject is not enrolled (experiment absent or not `running`).
27
+ */
28
+ export const exposureResult = v.union(
29
+ v.object({ variant: v.null() }),
30
+ v.object({ variant: v.string() }),
31
+ );
32
+
33
+ /** Projection of an experiment definition returned by `getExperiment` / `listExperiments`. */
34
+ export const experimentDef = v.object({
35
+ key: v.string(),
36
+ scope: v.string(),
37
+ status: experimentStatus,
38
+ variants: v.array(variant),
39
+ salt: v.string(),
40
+ createdAt: v.number(),
41
+ });
42
+
43
+ /** Projection of a subject's sticky assignment returned by `getAssignment`. */
44
+ export const assignmentProjection = v.object({
45
+ variant: v.string(),
46
+ assignedAt: v.number(),
47
+ });
48
+
49
+ /**
50
+ * Per-variant tally returned by `results`. `assigned` and `subjects` together with
51
+ * the configured `weight` let an analyst compute sample-ratio-mismatch (observed
52
+ * vs expected split) and the funnel denominator host-side.
53
+ */
54
+ export const variantResult = v.object({
55
+ /** The variant key. */
56
+ variant: v.string(),
57
+ /** Subjects assigned to this variant (the realized split for SRM). */
58
+ assigned: v.number(),
59
+ /** Distinct subjects exposed to this variant (the funnel denominator). */
60
+ subjects: v.number(),
61
+ /** Total exposure events recorded for this variant. */
62
+ exposures: v.number(),
63
+ /** The configured weight from the current definition (0 if the variant is gone). */
64
+ weight: v.number(),
65
+ });
@@ -0,0 +1,85 @@
1
+ // @vitest-environment jsdom
2
+
3
+ /**
4
+ * Tests for the optional `./react` front-tooling layer. Runs under jsdom (per-file
5
+ * pragma; the global vitest env is edge-runtime). `convex/react` is mocked so the
6
+ * hooks are exercised as thin pass-throughs to `useQuery`.
7
+ */
8
+
9
+ import { renderHook } from "@testing-library/react";
10
+ import { describe, expect, test, vi } from "vitest";
11
+ import type { FunctionReference } from "convex/server";
12
+ import { useQuery } from "convex/react";
13
+ import { useAssignment, useExperimentResults, useVariant } from "./index.js";
14
+ import type { Assignment, VariantResult } from "../client/types.js";
15
+
16
+ vi.mock("convex/react", () => ({ useQuery: vi.fn() }));
17
+ const useQueryMock = vi.mocked(useQuery);
18
+
19
+ const peekRef = "experiments.peek" as unknown as FunctionReference<
20
+ "query",
21
+ "public",
22
+ { scope?: string; key: string; subjectRef: string },
23
+ { variant: string | null }
24
+ >;
25
+ const assignmentRef = "experiments.getAssignment" as unknown as FunctionReference<
26
+ "query",
27
+ "public",
28
+ { scope?: string; key: string; subjectRef: string },
29
+ Assignment | null
30
+ >;
31
+ const resultsRef = "experiments.results" as unknown as FunctionReference<
32
+ "query",
33
+ "public",
34
+ { scope?: string; key: string },
35
+ VariantResult[]
36
+ >;
37
+
38
+ describe("useVariant", () => {
39
+ test("returns undefined while loading", () => {
40
+ useQueryMock.mockReturnValue(undefined);
41
+ const { result } = renderHook(() =>
42
+ useVariant(peekRef, { key: "exp", subjectRef: "u1" }),
43
+ );
44
+ expect(useQueryMock).toHaveBeenCalledWith(peekRef, { key: "exp", subjectRef: "u1" });
45
+ expect(result.current).toBeUndefined();
46
+ });
47
+
48
+ test("returns the variant key when enrolled", () => {
49
+ useQueryMock.mockReturnValue({ variant: "treatment" });
50
+ const { result } = renderHook(() =>
51
+ useVariant(peekRef, { key: "exp", subjectRef: "u1" }),
52
+ );
53
+ expect(result.current).toBe("treatment");
54
+ });
55
+
56
+ test("returns null when not enrolled", () => {
57
+ useQueryMock.mockReturnValue({ variant: null });
58
+ const { result } = renderHook(() =>
59
+ useVariant(peekRef, { key: "exp", subjectRef: "u1" }),
60
+ );
61
+ expect(result.current).toBeNull();
62
+ });
63
+ });
64
+
65
+ describe("useAssignment", () => {
66
+ test("forwards to useQuery and returns its data", () => {
67
+ const data: Assignment = { variant: "control", assignedAt: 1 };
68
+ useQueryMock.mockReturnValue(data);
69
+ const { result } = renderHook(() =>
70
+ useAssignment(assignmentRef, { key: "exp", subjectRef: "u1" }),
71
+ );
72
+ expect(result.current).toBe(data);
73
+ });
74
+ });
75
+
76
+ describe("useExperimentResults", () => {
77
+ test("forwards to useQuery and returns its data", () => {
78
+ const data: VariantResult[] = [
79
+ { variant: "control", assigned: 1, subjects: 1, exposures: 2, weight: 1 },
80
+ ];
81
+ useQueryMock.mockReturnValue(data);
82
+ const { result } = renderHook(() => useExperimentResults(resultsRef, { key: "exp" }));
83
+ expect(result.current).toBe(data);
84
+ });
85
+ });
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Optional, tree-shakeable React front-tooling for `@vllnt/convex-experiments`.
3
+ *
4
+ * Thin reactive hooks over `useQuery` from `convex/react`. Each takes the HOST's
5
+ * re-exported query reference plus its args — the component never imports the host
6
+ * `api`. `react` and `convex/react` are optional peer deps: a backend-only consumer
7
+ * pulls none of this code.
8
+ *
9
+ * NO-LEAK CONTRACT: these hooks expose only non-secret experiment data — the
10
+ * subject's own variant key, their assignment, and aggregate per-variant tallies.
11
+ * There is no secret or cross-subject payload. `useVariant` reads the deterministic
12
+ * `peek` query, so it paints the correct variant on first render (no flash of
13
+ * control); call the `logExposure` mutation to enroll + tally.
14
+ */
15
+
16
+ import type { FunctionReference } from "convex/server";
17
+ import { useQuery } from "convex/react";
18
+ import type { Assignment, VariantResult } from "../client/types.js";
19
+
20
+ /**
21
+ * Reactive, flicker-free variant for a subject — wraps the host's re-exported
22
+ * `peek` query (deterministic, read-only). Returns the variant key, `null` when not
23
+ * enrolled, or `undefined` while the query loads.
24
+ */
25
+ export function useVariant(
26
+ peekRef: FunctionReference<
27
+ "query",
28
+ "public",
29
+ { scope?: string; key: string; subjectRef: string },
30
+ { variant: string | null }
31
+ >,
32
+ args: { scope?: string; key: string; subjectRef: string },
33
+ ): string | null | undefined {
34
+ const result = useQuery(peekRef, args);
35
+ return result === undefined ? undefined : result.variant;
36
+ }
37
+
38
+ /**
39
+ * Reactive sticky assignment — wraps the host's re-exported `getAssignment` query.
40
+ * `null` when not enrolled, `undefined` while loading.
41
+ */
42
+ export function useAssignment(
43
+ getAssignmentRef: FunctionReference<
44
+ "query",
45
+ "public",
46
+ { scope?: string; key: string; subjectRef: string },
47
+ Assignment | null
48
+ >,
49
+ args: { scope?: string; key: string; subjectRef: string },
50
+ ): Assignment | null | undefined {
51
+ return useQuery(getAssignmentRef, args);
52
+ }
53
+
54
+ /**
55
+ * Reactive per-variant tallies (`assigned`/`subjects`/`exposures`/`weight`) for a
56
+ * live results dashboard — wraps the host's re-exported `results` query.
57
+ */
58
+ export function useExperimentResults(
59
+ resultsRef: FunctionReference<
60
+ "query",
61
+ "public",
62
+ { scope?: string; key: string },
63
+ VariantResult[]
64
+ >,
65
+ args: { scope?: string; key: string },
66
+ ): VariantResult[] | undefined {
67
+ return useQuery(resultsRef, args);
68
+ }
package/src/shared.ts ADDED
@@ -0,0 +1,69 @@
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
+ /** Default page size for a `deleteExperiment` cascade pass before it self-reschedules. */
12
+ export const DEFAULT_DELETE_BATCH = 200;
13
+
14
+ /** A weighted variant: an opaque variant key and its relative selection weight. */
15
+ export interface Variant {
16
+ /** The host's opaque variant key (e.g. `"control"`, `"treatment"`). */
17
+ key: string;
18
+ /** Relative selection weight; the bucket width is `weight / sum(weights)`. */
19
+ weight: number;
20
+ }
21
+
22
+ /**
23
+ * FNV-1a 32-bit hash of `input`, returned as an unsigned integer. Deterministic,
24
+ * synchronous, and dependency-free — the component runs in a V8 isolate, so a
25
+ * pure string hash (rather than async `crypto.subtle`) is what keeps variant
26
+ * assignment a plain function callable inside a mutation.
27
+ */
28
+ export function fnv1a(input: string): number {
29
+ let hash = 0x811c9dc5;
30
+ for (let i = 0; i < input.length; i++) {
31
+ hash ^= input.charCodeAt(i);
32
+ hash = Math.imul(hash, 0x01000193);
33
+ }
34
+ return hash >>> 0;
35
+ }
36
+
37
+ /**
38
+ * Deterministically pick a variant for `subjectRef` from `variants`, weighted by
39
+ * each variant's `weight`. The same `(salt, subjectRef)` always maps to the same
40
+ * variant — sticky assignment with no storage — and the distribution matches the
41
+ * weights. The component folds `scope` into the salt so the same subject buckets
42
+ * independently per scope. Assumes a non-empty `variants` with positive weights;
43
+ * the caller validates that upstream.
44
+ */
45
+ export function pickVariant(
46
+ variants: readonly Variant[],
47
+ salt: string,
48
+ subjectRef: string,
49
+ ): string {
50
+ const lastVariant = variants[variants.length - 1];
51
+ if (lastVariant === undefined) {
52
+ throw new Error("pickVariant requires at least one variant");
53
+ }
54
+ let total = 0;
55
+ for (const variant of variants) {
56
+ total += variant.weight;
57
+ }
58
+ // Map the hash into [0, total): a point on the cumulative-weight line.
59
+ let target = (fnv1a(`${salt}:${subjectRef}`) / 0x100000000) * total;
60
+ // Walk every variant but the last, subtracting its bucket width.
61
+ for (const variant of variants.slice(0, -1)) {
62
+ target -= variant.weight;
63
+ if (target < 0) {
64
+ return variant.key;
65
+ }
66
+ }
67
+ // The point fell in the final variant's bucket (also the single-variant case).
68
+ return lastVariant.key;
69
+ }
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
+ }
@@ -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
+ });