Skip to content

Open source CapCut alternative.

TypeScript

feat(site): nightly experiment results

David Le12292dc119b5
diff --git a/site/src/app/api/experiments/results/route.ts b/site/src/app/api/experiments/results/route.ts
new file mode 100644
index 00000000..f1ebe624
--- /dev/null
+++ b/site/src/app/api/experiments/results/route.ts
@@ -0,0 +1,16 @@
+import { NextRequest, NextResponse } from "next/server";
+
+import { isVercelCron, notFoundResponse } from "@/lib/donkey-api-auth";
+import { enqueueJob } from "@/lib/jobs/queue";
+
+// Without a queue configured (local dev) the job runs inline before the
+// response; give it room.
+export const maxDuration = 300;
+
+// The nightly results run for every live experiment. Vercel's cron
+// authenticates with the CRON_SECRET bearer token; a run for one experiment
+// starts from su through POST /api/jobs.
+export const GET = async (request: NextRequest) => {
+ if (!isVercelCron(request)) return notFoundResponse();
+ return NextResponse.json(await enqueueJob("experiment-results", {}, "vercel-cron"));
+};
diff --git a/site/src/lib/analytics/posthog.ts b/site/src/lib/analytics/posthog.ts
index 4c1a01ff..37908f74 100644
--- a/site/src/lib/analytics/posthog.ts
+++ b/site/src/lib/analytics/posthog.ts
@@ -79,3 +79,45 @@ export async function fetchActiveDistinctIds(day: string): Promise<string[]> {
}
return [...ids].sort();
}
+
+const hogqlString = (value: string) => `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
+
+const hogqlTime = (at: Date) => `toDateTime('${at.toISOString().slice(0, 19).replace("T", " ")}', 'UTC')`;
+
+// Each account carries its own cutoff, so the clauses go in an OR list rather
+// than one shared threshold; a chunk this size keeps the query well inside
+// PostHog's limits.
+const ID_CHUNK = 200;
+
+/** Which of these accounts fired the event at or after their own `since`.
+ * An account that fired it only before its cutoff is absent. */
+export async function fetchConvertedAfter(
+ event: string,
+ entries: { distinctId: string; since: Date }[],
+): Promise<Set<string>> {
+ const apiKey = process.env.POSTHOG_PERSONAL_API_KEY;
+ const projectId = posthogProjectId();
+ if (!apiKey || projectId === undefined) {
+ throw new Error("PostHog query access is not configured.");
+ }
+ const converted = new Set<string>();
+ for (let i = 0; i < entries.length; i += ID_CHUNK) {
+ const chunk = entries.slice(i, i + ID_CHUNK);
+ const clauses = chunk
+ .map((e) => `(distinct_id = ${hogqlString(e.distinctId)} AND timestamp >= ${hogqlTime(e.since)})`)
+ .join(" OR ");
+ const query = [
+ "SELECT DISTINCT distinct_id FROM events",
+ `WHERE event = ${hogqlString(event)}`,
+ `AND (${clauses})`,
+ `LIMIT ${ID_CHUNK}`,
+ ].join(" ");
+ const res = await postQuery(projectId, apiKey, query);
+ const data = (await res.json()) as { results?: unknown[][] };
+ for (const row of data.results ?? []) {
+ const id = row?.[0];
+ if (typeof id === "string" && id) converted.add(id);
+ }
+ }
+ return converted;
+}
diff --git a/site/src/lib/jobs/experiment-results.ts b/site/src/lib/jobs/experiment-results.ts
new file mode 100644
index 00000000..85bc4d29
--- /dev/null
+++ b/site/src/lib/jobs/experiment-results.ts
@@ -0,0 +1,128 @@
+import { z } from "zod";
+
+import type { Prisma } from "@/generated/prisma/client";
+import { fetchConvertedAfter, isPosthogQueryConfigured } from "@/lib/analytics/posthog";
+import { getGlobalSetting } from "@/lib/config/effective";
+import { parseVariants } from "@/lib/config/effective";
+import { metricSchema, type ExperimentMetric } from "@/lib/config/experiment";
+import { PURCHASE_SOURCES } from "@/lib/config/purchases";
+import { computeResults, type Thresholds, type VariantCount } from "@donkeycut/abexp";
+import { defineJob, JobFailure } from "@/lib/jobs/registry";
+import { prisma } from "@/lib/prisma";
+
+// Computes each experiment's read and stores it on the row: for every metric,
+// how many exposed accounts in each variant converted after their exposure,
+// and the verdict that follows. Runs nightly for every experiment that is
+// running, paused, or recently ended, and on demand from su for one.
+
+type Exposure = { userId: string; variant: string; exposedAt: Date };
+
+// Postgres binds every id in an IN list, so the accounts go in chunks.
+const USER_CHUNK = 500;
+
+/** The accounts that converted at or after their own exposure. A conversion
+ * before an account was exposed is not this experiment's doing, and a later
+ * one still counts — an account enrolled late has usually acted before. */
+async function convertedUsers(metric: ExperimentMetric, exposures: Exposure[]): Promise<Set<string>> {
+ if (exposures.length === 0) return new Set();
+ if (metric.source === "event") {
+ return fetchConvertedAfter(
+ metric.event!,
+ exposures.map((e) => ({ distinctId: e.userId, since: e.exposedAt })),
+ );
+ }
+ const exposedAt = new Map(exposures.map((e) => [e.userId, e.exposedAt]));
+ const converted = new Set<string>();
+ const ids = [...exposedAt.keys()];
+ for (let i = 0; i < ids.length; i += USER_CHUNK) {
+ const chunk = ids.slice(i, i + USER_CHUNK);
+ const grants = await prisma.userCreditGrant.findMany({
+ where: { userId: { in: chunk }, source: { in: [...PURCHASE_SOURCES] } },
+ select: { userId: true, createdAt: true },
+ });
+ for (const grant of grants) {
+ const since = exposedAt.get(grant.userId);
+ if (since && grant.createdAt.getTime() >= since.getTime()) converted.add(grant.userId);
+ }
+ }
+ return converted;
+}
+
+export async function computeExperimentResults(experimentId: string): Promise<{ key: string; verdict: string }> {
+ const bars = await getGlobalSetting("experimentResults");
+ const experiment = await prisma.experiment.findUnique({
+ where: { id: experimentId },
+ select: { id: true, key: true, variants: true, metrics: true },
+ });
+ if (!experiment) throw new JobFailure(`Experiment ${experimentId} does not exist.`);
+ const variants = parseVariants(experiment.variants);
+ const control = variants[0]?.key;
+ if (!control) throw new JobFailure(`Experiment ${experiment.key} has no variants.`);
+ const metrics = metricSchema.array().safeParse(experiment.metrics);
+ if (!metrics.success) throw new JobFailure(`Experiment ${experiment.key} has metrics that no longer parse.`);
+
+ // Only what the hash assigned and the app showed counts; a row written from
+ // su, a held-out account, and an unexposed assignment are left out.
+ const [rows, holdouts] = await Promise.all([
+ prisma.experimentAssignment.findMany({
+ where: { experimentId, manual: false, variant: { not: null }, exposedAt: { not: null } },
+ select: { userId: true, variant: true, exposedAt: true },
+ }),
+ prisma.experimentHoldout.findMany({ select: { userId: true } }),
+ ]);
+ const held = new Set(holdouts.map((h) => h.userId));
+ const exposures: Exposure[] = rows
+ .filter((r) => !held.has(r.userId))
+ .map((r) => ({ userId: r.userId, variant: r.variant!, exposedAt: r.exposedAt! }));
+ const notes: string[] = [];
+ const measured: { metric: ExperimentMetric; counts: VariantCount[] }[] = [];
+ for (const metric of metrics.data) {
+ if (metric.source === "event" && !isPosthogQueryConfigured()) {
+ notes.push(`${metric.name}: PostHog query access is not configured, so this event metric was skipped.`);
+ continue;
+ }
+ const converted = await convertedUsers(metric, exposures);
+ const counts: VariantCount[] = variants.map((v) => ({ key: v.key, exposed: 0, converted: 0 }));
+ const byKey = new Map(counts.map((c) => [c.key, c]));
+ for (const exposure of exposures) {
+ const count = byKey.get(exposure.variant);
+ if (!count) continue;
+ count.exposed += 1;
+ if (converted.has(exposure.userId)) count.converted += 1;
+ }
+ measured.push({ metric, counts });
+ }
+
+ const results = computeResults({
+ computedAt: new Date(),
+ control,
+ metrics: measured,
+ notes,
+ thresholds: bars as Thresholds,
+ });
+ await prisma.experiment.update({
+ where: { id: experimentId },
+ data: { results: results as unknown as Prisma.InputJsonValue, resultsAt: new Date(results.computedAt) },
+ });
+ return { key: experiment.key, verdict: results.verdict.state };
+}
+
+export const experimentResultsJob = defineJob(
+ z.object({ experimentId: z.string().min(1).optional() }).strict(),
+ async (payload) => {
+ if (payload.experimentId) {
+ return { computed: [await computeExperimentResults(payload.experimentId)] };
+ }
+ const { graceDays } = await getGlobalSetting("experimentResults");
+ const endedAfter = new Date(Date.now() - graceDays * 86_400_000);
+ const rows = await prisma.experiment.findMany({
+ where: {
+ OR: [{ status: { in: ["running", "paused"] } }, { status: "ended", endedAt: { gte: endedAfter } }],
+ },
+ select: { id: true },
+ });
+ const computed = [];
+ for (const row of rows) computed.push(await computeExperimentResults(row.id));
+ return { computed };
+ },
+);
diff --git a/site/src/lib/jobs/registry.ts b/site/src/lib/jobs/registry.ts
index 20e8348e..c06c57d0 100644
--- a/site/src/lib/jobs/registry.ts
+++ b/site/src/lib/jobs/registry.ts
@@ -3,6 +3,7 @@ import type { z } from "zod";
import type { Prisma } from "@/generated/prisma/client";
import { analyticsDailyJob } from "@/lib/jobs/analytics-daily";
import { deleteUserJob } from "@/lib/jobs/delete-user";
+import { experimentResultsJob } from "@/lib/jobs/experiment-results";
import { outreachScanJob } from "@/lib/jobs/outreach-scan";
// Thrown by an executor when the job can never succeed — the message lands on
@@ -27,5 +28,6 @@ export function defineJob<S extends z.ZodType<unknown>>(
export const jobKinds: Record<string, JobKind> = {
"analytics-daily": analyticsDailyJob,
"delete-user": deleteUserJob,
+ "experiment-results": experimentResultsJob,
"outreach-scan": outreachScanJob,
};
diff --git a/site/vercel.json b/site/vercel.json
index 18f8392a..06d56b06 100644
--- a/site/vercel.json
+++ b/site/vercel.json
@@ -2,6 +2,7 @@
"crons": [
{ "path": "/api/cut-cloud/gc", "schedule": "0 4 * * *" },
{ "path": "/api/analytics/run", "schedule": "0 1 * * *" },
+ { "path": "/api/experiments/results", "schedule": "0 3 * * *" },
{ "path": "/api/marketing/outreach/scan", "schedule": "0 2 * * *" }
]
}