Open source CapCut alternative.
TypeScript
fix(site): retry credit write conflicts with backoff
David Le26787b49d78e
diff --git a/site/src/lib/credits/inference.test.ts b/site/src/lib/credits/inference.test.tsnew file mode 100644index 00000000..5ab9927d--- /dev/null+++ b/site/src/lib/credits/inference.test.ts@@ -0,0 +1,69 @@+import { describe, expect, test } from "bun:test";++import { Prisma } from "@/generated/prisma/client";+import { stubModule } from "@/lib/testing/stubModule";++// A charge is one Serializable transaction on the account. Concurrent charges+// for one account conflict, and Postgres reports it two ways: Prisma's P2034,+// or the driver adapter's raw TransactionWriteConflict at commit.++const recorded = { creditCostMicros: BigInt(0), remainingBalanceMicros: BigInt(0), usageEventId: "event" };+let failures: Error[] = [];+let attempts = 0;+const prisma = {+ $transaction: async () => {+ attempts += 1;+ const failure = failures.shift();+ if (failure) {+ throw failure;+ }+ return recorded;+ },+};++await stubModule<typeof import("@/lib/prisma")>("@/lib/prisma", import.meta.url, { prisma: prisma as never });+const { recordInferenceUsage } = await import("./inference");++const usage = {+ clientId: null,+ model: "model",+ provider: "provider",+ requestKind: "judge",+ route: "/api/inference/judge/",+ status: "failed",+ userId: "user",+} as const;++const knownConflict = () =>+ new Prisma.PrismaClientKnownRequestError("write conflict", { code: "P2034", clientVersion: "test" });++// The shape @prisma/driver-adapter-utils throws when the conflict lands on COMMIT.+const adapterConflict = () =>+ Object.assign(new Error("TransactionWriteConflict"), {+ name: "DriverAdapterError",+ cause: { kind: "TransactionWriteConflict", originalCode: "40001" },+ });++describe("recording usage under concurrent charges", () => {+ test("retries a conflict raised at commit by the driver adapter", async () => {+ failures = [adapterConflict()];+ attempts = 0;+ expect(await recordInferenceUsage(usage)).toEqual(recorded);+ expect(attempts).toBe(2);+ });++ test("outlasts a burst of conflicts from parallel judge calls", async () => {+ failures = Array.from({ length: 8 }, (_, i) => (i % 2 ? knownConflict() : adapterConflict()));+ attempts = 0;+ expect(await recordInferenceUsage(usage)).toEqual(recorded);+ expect(attempts).toBe(9);+ });++ test("throws any other error at once", async () => {+ const other = new Error("connection refused");+ failures = [other];+ attempts = 0;+ await expect(recordInferenceUsage(usage)).rejects.toBe(other);+ expect(attempts).toBe(1);+ });+});diff --git a/site/src/lib/credits/inference.ts b/site/src/lib/credits/inference.tsindex 12b13553..c4fef525 100644--- a/site/src/lib/credits/inference.ts+++ b/site/src/lib/credits/inference.ts@@ -403,25 +403,44 @@ export async function requireInferenceCredits(input: CreditPreflightInput) {}// Prisma raises P2034 when a transaction is aborted by a write conflict or-// deadlock. A Serializable transaction rolls back entirely on conflict, so-// nothing partially committed and the whole body is safe to re-run. Concurrent-// writers against the same credit account routinely collide here — two-// generations at once, the parallel signup grants, simultaneous Stripe webhook-// deliveries for one checkout — so every credit transaction retries-// transparently instead of surfacing the race to its caller.+// deadlock; a conflict detected at COMMIT arrives as the driver adapter's raw+// TransactionWriteConflict. A Serializable transaction rolls back+// entirely on conflict, so nothing partially committed and the whole body is+// safe to re-run. Concurrent writers against the same credit account routinely+// collide here — two generations at once, a stock search's parallel judge+// calls, the parallel signup grants, simultaneous Stripe webhook deliveries for+// one checkout — so every credit transaction retries transparently and the+// caller never sees the race.+const writeConflictMaxAttempts = 10;+const writeConflictBaseDelayMs = 20;+const writeConflictMaxDelayMs = 500;++function isWriteConflict(error: unknown) {+ if (error instanceof Prisma.PrismaClientKnownRequestError) {+ return error.code === "P2034";+ }+ if (!(error instanceof Error) || error.name !== "DriverAdapterError") {+ return false;+ }+ const cause = error.cause as { kind?: unknown } | undefined;+ return cause?.kind === "TransactionWriteConflict";+}+async function withWriteConflictRetry<T>(run: () => Promise<T>): Promise<T> {- const maxAttempts = 5;for (let attempt = 1; ; attempt += 1) {try {return await run();} catch (error) {- const isWriteConflict =- error instanceof Prisma.PrismaClientKnownRequestError &&- error.code === "P2034";- if (!isWriteConflict || attempt >= maxAttempts) {+ if (!isWriteConflict(error) || attempt >= writeConflictMaxAttempts) {throw error;}}++ // Back off with full jitter so the colliding writers spread out; an+ // immediate retry lands them on the same rows again. The first retry+ // waits up to 40 ms, the fifth and later up to 500 ms.+ const ceiling = Math.min(writeConflictMaxDelayMs, writeConflictBaseDelayMs * 2 ** attempt);+ await new Promise((resolve) => setTimeout(resolve, Math.random() * ceiling));}}