ISSUE DESCRIPTION magic-link verify deadlocks: runWithTransaction nests…
- User
ISSUE DESCRIPTION
magic-link verify deadlocks: runWithTransaction nests adapter.transaction (1.6.11 consumeVerificationValue) instead of reusing the active transaction
Is this suited for github?
- Yes, this is suited for github
Reproduction
- better-auth 1.6.11 with the
magicLinkplugin. - A database adapter whose
transactionis a real interactive DB transaction that holds a dedicated connection for its duration (e.g. the Kysely adapter, or@zenstackhq/better-auth, backed bypg). - Limit the client connection pool to one connection:
new Pool({ max: 1 })-- standard when using Cloudflare Hyperdrive, which pools server-side so the worker keeps a tiny client pool. await auth.api.signInMagicLink({ body: { email } })-> works (single insert).await auth.api.magicLinkVerify({ query: { token } })(orGET /api/auth/magic-link/verify?token=...).
Minimal trigger: any setup where
adapter.transactionacquires a connection and the pool cannot hand out two connections at once.Current vs. Expected behavior
Current: the verify call hangs forever and never returns. Postgres shows the backend stuck
idle in transaction(wait_event = ClientRead) right after the verificationSELECT; the connection is never released, so every attempt leaks one idle-in-transaction connection.Trace of the cause:
internalAdapter.consumeVerificationValue(added in 1.6.11) runs insiderunWithTransaction-> opens transaction tx1 (BEGIN, takes the only pooled connection).- Consuming the row (
consumeOne) triggers anotherrunWithTransaction-> callsadapter.transactionagain -> transaction tx2, which tries to acquire a second connection. runWithTransactionin@better-auth/core(context/transaction.mjs) always opens a freshadapter.transaction; it does NOT checkadapterAsyncStorage.getStore()to see whether a transaction is already active in the current async context. So tx2 is nested inside tx1 and blocks forever waiting for the connection tx1 holds -> deadlock.
Note the CRUD path already reuses the active transaction:
getCurrentAdapter(adapter)returns thetrxadapter from the ALS store.runWithTransactionis inconsistent with this -- it doesn't reuse.Expected:
runWithTransactionshould be reentrant -- when an adapter/transaction is already active in the async-context store, runfnwithin it instead of opening a nestedadapter.transaction(mirroringgetCurrentAdapter). Then verify needs only one connection and works on any pool size. (Alternatively/additionally, document that adapters MUST support reentrant nested transactions -- currently adapters like@zenstackhq/better-authopen a brand-new transaction on the base client for eachadapter.transactioncall, which is a reasonable contract but incompatible with the current nesting.)This is security-relevant: the 1.6.11 change that introduced this nesting was the magic-link "mint multiple sessions from one token" race fix, so the fix effectively breaks magic-link verification on connection-limited adapters/pools.
What version of Better Auth are you using?
1.6.11
System info
> The `auth info` CLI can't introspect this project headlessly because the auth instance is built dynamically via a factory (no static `auth.ts` export), so the values below are assembled manually { "better-auth": { "version": "1.6.11", "@better-auth/core": "1.6.11" }, "adapter": { "name": "@zenstackhq/better-auth", "version": "3.6.4", "orm": "@zenstackhq/orm 3.6.4 (Kysely 0.28.17)" }, "database": { "driver": "pg 8.20.0", "pool": { "max": 1 }, "fronted_by": "Cloudflare Hyperdrive" }, "runtime": { "platform": "Cloudflare Workers (workerd)", "wrangler": "4.95.0", "node_for_tooling": "v22.22.1" }, "plugins": ["magicLink"], "os": "macOS (Darwin 25.5.0)" }Which area(s) are affected? (Select all that apply)
Backend
Auth config (if applicable)
import { betterAuth } from "better-auth" export const auth = betterAuth({ emailAndPassword: { enabled: true }, });Additional context
- Bisected away unrelated suspects: the hang reproduces on older framework code and is independent of DI scope changes -- it's purely
1.6.10 -> 1.6.11. - Reproduced deterministically in a real
workerdintegration test (request magic link -> capture token -> verify) that times out before the change. - Relevant code:
@better-auth/corecontext/transaction.mjsrunWithTransaction(opensadapter.transactionunconditionally) vsgetCurrentAdapter(reuses the activetrx);internalAdapter.consumeVerificationValue->consumeOneWithHooks-> adapterconsumeOne. - Worked around downstream by making the adapter's transaction reentrant (reuse the in-flight transaction via
AsyncLocalStorage), which is also the correct semantics (nested transaction = one atomic unit) -- but it seems likerunWithTransactionitself should reuse the active transaction.
Interface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /better-auth, current file: none) bash-$
Assistant
Let's use the
editspecial command directly on the file.Assistant
Now let's check the dist/build files if there are compiled
.mjsversions that also need updating (since issue referencescontext/transaction.mjs).Assistant
Now let's find
getWithHooksandconsumeOneWithHooksdefinition to see if it callsrunWithTransactionagain (the nested call causing deadlock).Assistant
Good, no circular import risk. Now let's implement the fix in factory.ts to make the consumeOne/incrementOne fallbacks reentrant-safe by using
runWithTransaction+getCurrentAdapter.Assistant
The consumeOne fallback spans lines 1373-1410 (res = await withSpan through resultNeedsOutputTransform = false;). Let's verify exact boundaries.
Assistant
Good, matches lines 1373-1409 (res=... through the closing
);) plus 1410 resultNeedsOutputTransform. Let's replace lines 1373:1410.Assistant
Now let's do the same for incrementOne fallback.
Assistant
Lines 1506-1553 (through resultNeedsOutputTransform = false; at 1553). Let's confirm exact line number for that.
Assistant
Now replace lines 1506-1557 with the reentrant version.
Assistant
Both fallback paths are now reentrant-safe. Now let's check for other similar
adapter.transaction(direct calls elsewhere in the codebase that could suffer the same issue (e.g., in internal-adapter.ts line 124, sign-up.ts, organization plugin).Assistant
Let's build core package first and run these tests to check compile-correctness.
Assistant
Good, pnpm works now. Let's check node_modules already installed.
Assistant
Dependencies installed. Let's run type-check / tests for core package specifically.
Assistant
Type checks pass. Let's view the final code around both edits to make sure formatting is fine.
Assistant
Now let's run biome/format to fix indentation consistency and check the incrementOne block too.
Assistant
Good. Now let's run biome format to normalize style.
Assistant
Now let's run tests: core package's own tests plus adapter tests (memory-adapter, kysely-adapter, better-auth package tests related to magic-link/verification).
Assistant
Confirmed - these failures are pre-existing environment issues unrelated to our change. Let's restore our changes.
Assistant
All pass after building. Let's run the full core test suite again plus better-auth package tests relevant to magic-link and verification.
Assistant
All 26 test files pass now. Let's also run the better-auth package tests related to magic-link, verification, and transaction to ensure end-to-end correctness.
Assistant
Build succeeded. Now run relevant tests.
Assistant
Need to build @better-auth/telemetry too.
Assistant
All pass. Now let's write a quick reproduction script that simulates a connection-pool-limited custom adapter with a non-reentrant transaction, to confirm the deadlock is fixed.
Assistant
Let's place the script within the repo so node resolves workspace packages.
Assistant
With our fix and the freshly built core, the deadlock is resolved. Let's confirm it deadlocks WITHOUT our fix (stash again, rebuild, test).
Assistant
Confirmed: without the fix, this deterministically deadlocks (mirroring the exact issue). With the fix, it resolves correctly. Let's restore our changes and rebuild.
Assistant
Now let's remove the temporary repro script and clean up dist artifacts we don't want to commit (since dist wasn't part of repo originally, let's check git status).
Assistant
All organization tests pass. Now let's run the sign-up tests and the full adapter test suites (kysely, memory, prisma, drizzle, mongo) plus scim.
Assistant
All pass. Now let's run the full db/internal-adapter test suite and any transaction-related tests to be thorough.
Assistant
Confirmed pre-existing failures unrelated to our changes (missing postgres connection & mongo-adapter build artifact from environment setup). Our fix is restored. Let's do a final full diff review.
Assistant
Now let's find and update the incrementOne FIXME comment similarly.
Assistant
Now let's re-run tsc and tests to confirm nothing broke with the comment edits.
Assistant
All 415 tests pass across core, magic-link, email-verification, and internal-adapter. Let's do a final full diff review.
Assistant
This is a clean, focused fix. Let's also check that the
distfolders we generated during testing aren't tracked/staged, and clean up.Assistant
Clean — only the intended source changes are present. Let's run one more broad check with knip/lint to make sure nothing else complains, and a final biome lint check on modified files.
Assistant
Let's fix import ordering.
Assistant
Lint passes now. Let's rebuild core and rerun the full relevant test suite once more to make sure everything still works after the lint fix.
Assistant
All 38 test files (644 tests) pass. Let's do a final review of the complete diff.
Assistant
The changes are focused, minimal, and well-tested. Let me go through the checklist:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →