@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.
Files changed (50) hide show
  1. package/README.md +35 -6
  2. package/dist/client/index.d.ts +54 -3
  3. package/dist/client/index.d.ts.map +1 -1
  4. package/dist/client/index.js +53 -4
  5. package/dist/client/index.js.map +1 -1
  6. package/dist/client/types.d.ts +8 -3
  7. package/dist/client/types.d.ts.map +1 -1
  8. package/dist/component/_generated/component.d.ts +35 -0
  9. package/dist/component/_generated/component.d.ts.map +1 -1
  10. package/dist/component/_generated/server.d.ts +12 -0
  11. package/dist/component/_generated/server.d.ts.map +1 -1
  12. package/dist/component/_generated/server.js +2 -0
  13. package/dist/component/_generated/server.js.map +1 -1
  14. package/dist/component/convex.config.d.ts.map +1 -1
  15. package/dist/component/mutations.d.ts +46 -20
  16. package/dist/component/mutations.d.ts.map +1 -1
  17. package/dist/component/mutations.js +192 -23
  18. package/dist/component/mutations.js.map +1 -1
  19. package/dist/component/queries.d.ts +41 -8
  20. package/dist/component/queries.d.ts.map +1 -1
  21. package/dist/component/queries.js +81 -19
  22. package/dist/component/queries.js.map +1 -1
  23. package/dist/component/schema.d.ts +39 -17
  24. package/dist/component/schema.d.ts.map +1 -1
  25. package/dist/component/schema.js +19 -4
  26. package/dist/component/schema.js.map +1 -1
  27. package/dist/component/validators.d.ts +31 -18
  28. package/dist/component/validators.d.ts.map +1 -1
  29. package/dist/component/validators.js +14 -3
  30. package/dist/component/validators.js.map +1 -1
  31. package/dist/react/index.d.ts +57 -0
  32. package/dist/react/index.d.ts.map +1 -0
  33. package/dist/react/index.js +39 -0
  34. package/dist/react/index.js.map +1 -0
  35. package/dist/shared.d.ts +5 -3
  36. package/dist/shared.d.ts.map +1 -1
  37. package/dist/shared.js +5 -3
  38. package/dist/shared.js.map +1 -1
  39. package/package.json +34 -15
  40. package/src/client/index.ts +98 -4
  41. package/src/client/types.ts +8 -3
  42. package/src/component/_generated/component.ts +42 -1
  43. package/src/component/_generated/server.ts +13 -0
  44. package/src/component/mutations.ts +219 -23
  45. package/src/component/queries.ts +95 -18
  46. package/src/component/schema.ts +20 -4
  47. package/src/component/validators.ts +14 -3
  48. package/src/react/index.test.tsx +85 -0
  49. package/src/react/index.tsx +68 -0
  50. package/src/shared.ts +6 -3
@@ -1,8 +1,11 @@
1
1
  import { v } from "convex/values";
2
2
  import { query } from "./_generated/server";
3
+ import { pickVariant } from "../shared";
3
4
  import {
4
5
  assignmentProjection,
5
6
  experimentDef,
7
+ experimentStatus,
8
+ exposureResult,
6
9
  variantResult,
7
10
  } from "./validators";
8
11
 
@@ -31,6 +34,30 @@ export const getExperiment = query({
31
34
  },
32
35
  });
33
36
 
37
+ /** Every experiment in a scope, optionally filtered by `status`. */
38
+ export const listExperiments = query({
39
+ args: { scope: v.string(), status: v.optional(experimentStatus) },
40
+ returns: v.array(experimentDef),
41
+ handler: async (ctx, args) => {
42
+ const rows = await ctx.db
43
+ .query("experiments")
44
+ .withIndex("by_scope", (q) => q.eq("scope", args.scope))
45
+ .collect();
46
+ const filtered =
47
+ args.status === undefined
48
+ ? rows
49
+ : rows.filter((row) => row.status === args.status);
50
+ return filtered.map((row) => ({
51
+ key: row.key,
52
+ scope: row.scope,
53
+ status: row.status,
54
+ variants: row.variants,
55
+ salt: row.salt,
56
+ createdAt: row.createdAt,
57
+ }));
58
+ },
59
+ });
60
+
34
61
  /** A subject's sticky assignment for an experiment, or `null` if not enrolled. */
35
62
  export const getAssignment = query({
36
63
  args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
@@ -53,32 +80,82 @@ export const getAssignment = query({
53
80
  });
54
81
 
55
82
  /**
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.
83
+ * Read-only deterministic variant for a subject — the sticky variant **without
84
+ * persisting** anything. Returns the stored assignment if one exists, otherwise
85
+ * the deterministic `pickVariant` result; `{ variant: null }` when the experiment
86
+ * is absent or not `running`. Use this for SSR / server-component render and as a
87
+ * flicker-free first paint; call the `logExposure` mutation to enroll + tally.
88
+ */
89
+ export const peek = query({
90
+ args: { scope: v.string(), key: v.string(), subjectRef: v.string() },
91
+ returns: exposureResult,
92
+ handler: async (ctx, args) => {
93
+ const experiment = await ctx.db
94
+ .query("experiments")
95
+ .withIndex("by_scope_key", (q) =>
96
+ q.eq("scope", args.scope).eq("key", args.key),
97
+ )
98
+ .unique();
99
+ if (experiment === null || experiment.status !== "running") {
100
+ return { variant: null };
101
+ }
102
+ const assignment = await ctx.db
103
+ .query("assignments")
104
+ .withIndex("by_scope_experiment_subject", (q) =>
105
+ q
106
+ .eq("scope", args.scope)
107
+ .eq("experimentKey", args.key)
108
+ .eq("subjectRef", args.subjectRef),
109
+ )
110
+ .unique();
111
+ if (assignment !== null) {
112
+ return { variant: assignment.variant };
113
+ }
114
+ return {
115
+ variant: pickVariant(
116
+ experiment.variants,
117
+ `${experiment.scope}:${experiment.salt}`,
118
+ args.subjectRef,
119
+ ),
120
+ };
121
+ },
122
+ });
123
+
124
+ /**
125
+ * Per-variant tallies for an experiment — `assigned`, distinct `subjects` exposed,
126
+ * total `exposures`, and the configured `weight` (for sample-ratio-mismatch).
127
+ * Reads the maintained `variantTallies` rows (O(variants)), never scanning the
128
+ * exposure table. An experiment with no enrollment returns an empty array.
60
129
  */
61
130
  export const results = query({
62
131
  args: { scope: v.string(), key: v.string() },
63
132
  returns: v.array(variantResult),
64
133
  handler: async (ctx, args) => {
65
- const rows = await ctx.db
66
- .query("exposures")
134
+ const experiment = await ctx.db
135
+ .query("experiments")
136
+ .withIndex("by_scope_key", (q) =>
137
+ q.eq("scope", args.scope).eq("key", args.key),
138
+ )
139
+ .unique();
140
+ if (experiment === null) {
141
+ return [];
142
+ }
143
+ const tallies = await ctx.db
144
+ .query("variantTallies")
67
145
  .withIndex("by_scope_experiment", (q) =>
68
146
  q.eq("scope", args.scope).eq("experimentKey", args.key),
69
147
  )
70
148
  .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
- }));
149
+ const byVariant = new Map(tallies.map((tally) => [tally.variant, tally]));
150
+ return experiment.variants.map((variant) => {
151
+ const tally = byVariant.get(variant.key);
152
+ return {
153
+ variant: variant.key,
154
+ assigned: tally?.assigned ?? 0,
155
+ subjects: tally?.subjects ?? 0,
156
+ exposures: tally?.exposures ?? 0,
157
+ weight: variant.weight,
158
+ };
159
+ });
83
160
  },
84
161
  });
@@ -7,9 +7,12 @@ import { variant } from "./validators";
7
7
  * touched. An experiment is unique within a `scope`; `subjectRef`, variant keys,
8
8
  * and the scope are all opaque host-owned strings.
9
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).
10
+ * - `experiments` — the experiment definition (variants, weights, lifecycle, salt).
11
+ * - `assignments` — a subject's sticky variant choice, persisted on first `assign`.
12
+ * - `exposures` — a deduped per-subject exposure tally (the measurable surface).
13
+ * - `variantTallies` — one row per `(scope, experiment, variant)` holding running
14
+ * `assigned` / `subjects` (distinct exposed) / `exposures` counts, maintained on
15
+ * write so `results` reads O(variants) rows instead of scanning every exposure.
13
16
  */
14
17
  export default defineSchema({
15
18
  experiments: defineTable({
@@ -23,7 +26,9 @@ export default defineSchema({
23
26
  variants: v.array(variant),
24
27
  salt: v.string(),
25
28
  createdAt: v.number(),
26
- }).index("by_scope_key", ["scope", "key"]),
29
+ })
30
+ .index("by_scope_key", ["scope", "key"])
31
+ .index("by_scope", ["scope"]),
27
32
 
28
33
  assignments: defineTable({
29
34
  scope: v.string(),
@@ -52,4 +57,15 @@ export default defineSchema({
52
57
  "subjectRef",
53
58
  ])
54
59
  .index("by_scope_experiment", ["scope", "experimentKey"]),
60
+
61
+ variantTallies: defineTable({
62
+ scope: v.string(),
63
+ experimentKey: v.string(),
64
+ variant: v.string(),
65
+ assigned: v.number(),
66
+ subjects: v.number(),
67
+ exposures: v.number(),
68
+ })
69
+ .index("by_scope_experiment_variant", ["scope", "experimentKey", "variant"])
70
+ .index("by_scope_experiment", ["scope", "experimentKey"]),
55
71
  });
@@ -21,13 +21,16 @@ export const assignResult = v.union(
21
21
  v.object({ variant: v.string(), isNew: v.boolean() }),
22
22
  );
23
23
 
24
- /** Result of `logExposure`: the enrolled variant, or `null` when not enrolled. */
24
+ /**
25
+ * Result of `logExposure` / `peek`: the enrolled variant, or `null` when the
26
+ * subject is not enrolled (experiment absent or not `running`).
27
+ */
25
28
  export const exposureResult = v.union(
26
29
  v.object({ variant: v.null() }),
27
30
  v.object({ variant: v.string() }),
28
31
  );
29
32
 
30
- /** Projection of an experiment definition returned by `getExperiment`. */
33
+ /** Projection of an experiment definition returned by `getExperiment` / `listExperiments`. */
31
34
  export const experimentDef = v.object({
32
35
  key: v.string(),
33
36
  scope: v.string(),
@@ -43,12 +46,20 @@ export const assignmentProjection = v.object({
43
46
  assignedAt: v.number(),
44
47
  });
45
48
 
46
- /** Per-variant exposure tally returned by `results`. */
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
+ */
47
54
  export const variantResult = v.object({
48
55
  /** The variant key. */
49
56
  variant: v.string(),
57
+ /** Subjects assigned to this variant (the realized split for SRM). */
58
+ assigned: v.number(),
50
59
  /** Distinct subjects exposed to this variant (the funnel denominator). */
51
60
  subjects: v.number(),
52
61
  /** Total exposure events recorded for this variant. */
53
62
  exposures: v.number(),
63
+ /** The configured weight from the current definition (0 if the variant is gone). */
64
+ weight: v.number(),
54
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 CHANGED
@@ -8,6 +8,9 @@ export const DEFAULT_SCOPE = "global";
8
8
  /** Lifecycle status the client applies to `define` when the caller omits one. */
9
9
  export const DEFAULT_STATUS = "running";
10
10
 
11
+ /** Default page size for a `deleteExperiment` cascade pass before it self-reschedules. */
12
+ export const DEFAULT_DELETE_BATCH = 200;
13
+
11
14
  /** A weighted variant: an opaque variant key and its relative selection weight. */
12
15
  export interface Variant {
13
16
  /** The host's opaque variant key (e.g. `"control"`, `"treatment"`). */
@@ -35,9 +38,9 @@ export function fnv1a(input: string): number {
35
38
  * Deterministically pick a variant for `subjectRef` from `variants`, weighted by
36
39
  * each variant's `weight`. The same `(salt, subjectRef)` always maps to the same
37
40
  * 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
+ * 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.
41
44
  */
42
45
  export function pickVariant(
43
46
  variants: readonly Variant[],