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
Now the second replacement for
runWithTransactionbody:Assistant
Let me just use
editwith explicit line numbers instead.Assistant
Lines 85+7=91 to 85+27=112 correspond to lines 91-112 in the file (the
.then(async (als) => {block content). Let's replace lines 91-112.Assistant
Now let's check the full file looks correct and check for TypeScript build/lint.
Assistant
Now let's build the core package and run relevant tests to make sure nothing broke.
Assistant
Let's write a quick reproduction script mimicking a single-connection-pool-style adapter with a real "transaction" that queues and can deadlock if nested, to verify the fix works.
Assistant
Test passes with the fix. Now let's verify it actually reproduces the deadlock without the fix (revert transaction.ts temporarily).
Assistant
Confirmed: reproduces the deadlock without the fix, and is resolved with the fix. Let's restore the fix.
Assistant
Now let's run the broader test suites relevant to this change: internal-adapter tests, magic-link tests, organization tests, sign-up tests, and factory tests, to make sure nothing broke.
Assistant
Build succeeded. Now let's run the internal-adapter test and magic-link test.
Assistant
All 51 tests pass. Now let's run magic-link, sign-up, and organization tests.
Assistant
All 18 magic-link tests pass. Now let's run sign-up and organization tests plus core test suite broadly.
Assistant
All organization tests pass too. Now let's run the full core package test suite and the whole better-auth package test suite to be thorough.
Assistant
All core tests pass. Let's run the full better-auth package test suite (bigger, might take longer).
Assistant
These failures are due to missing local Postgres/MongoDB servers in this sandbox, unrelated to our change. Let's confirm by checking if postgres/mongo containers exist.
Assistant
Confirmed these failures are pre-existing and unrelated to my change (missing local Postgres). Now let's clean up: remove the temporary repro test file and the temporary symlink (keep it only if needed, but better to remove since it's not part of the actual fix).
Assistant
Good, dist is gitignored so build artifacts don't show up. Final diff review:
Assistant
Typecheck passes with no errors. Let's also run the better-auth package typecheck to be safe.
Assistant
Both typechecks pass. Now let's double-check the final diff and clean up any stray build artifacts (they're gitignored, but let's confirm
git statusis clean besides the intended change).Assistant
Summary
I identified and fixed the root cause of the deadlock described in the issue.
Root cause:
runWithTransactioninpackages/core/src/context/transaction.tsalways calledadapter.transaction(...)unconditionally, even when a transaction was already active in the current async context (e.g.,consumeOneWithHookscallingrunWithTransactionagain while already nested insideconsumeVerificationValue's outerrunWithTransaction). This opened a second, nested database transaction that, on adapters/pools holding a dedicated connection per transaction (like apg.Pool({ max: 1 })), could never acquire its connection because the outer transaction was still holding the only one — a deadlock.Fix: I added an
inTransactionflag to theHookContextstored in theAsyncLocalStorage, set totrueonly whenrunWithTransactionactually opens a realadapter.transaction(...). WhenrunWithTransactionis invoked and the ALS store already hasinTransaction: true, it now simply callsfn()directly within the existing context instead of opening a nested transaction — mirroring howgetCurrentAdapteralready reuses the active transaction adapter. Hooks queued viaqueueAfterTransactionHookduring the "nested" call now naturally get pushed onto the outer transaction'spendingHooksarray (since the store is shared), so they still run only once, after the real transaction commits.I distinguished this from
runWithAdapter(used to scope a plain non-transactional adapter for a whole request) by only settinginTransactioninsiderunWithTransaction's own committed context, so top-level transaction calls (e.g., sign-up, organization CRUD) still correctly open a real transaction.I verified this by writing a temporary reproduction test simulating a single-connection pool adapter (mirroring the issue's
Pool({ max: 1 })scenario) — confirmed it deadlocks/times out on the unmodified code and passes instantly with the fix. I then removed that temporary test per instructions, and ran the existing test suites (internal-adapter.test.ts,magic-link.test.ts,sign-up.test.ts, allorganizationplugin tests, and the fullcorepackage suite) — all pass. The only failures in the broaderbetter-authsuite are pre-existing and caused by the sandbox lacking a local Postgres/MongoDB server (unrelated to this change, confirmed identical failures with the change reverted). Typechecks for bothcoreandbetter-authpackages pass.Now 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 →