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 the adapter from the ALS store. is inconsistent with this -- it doesn't reuse. Assistant
Let me start by understanding the repository structure and the issue. The issue is about a deadlock in
runWithTransactionin the@better-auth/corepackage. TherunWithTransactionfunction always opens a newadapter.transactioninstead of checking if there's already an active transaction in the async context store. This causes a deadlock when the connection pool is limited to one connection.Let me first explore the repository structure and find the relevant files.
Assistant
I need to combine into a single command.
Assistant
Let me find the relevant files for the transaction and the magic link/verification code
Assistant
Let me look at the transaction.ts file and also search for related files.
Assistant
Let me look at the transaction.ts file and also find the magic-link plugin source code.
Assistant
Let me see the rest of the file and also find the consumeVerificationValue function
Assistant
Now I can see the issue. The
runWithTransactionalways callsadapter.transaction()(line 91) which opens a new DB transaction, without checking if there's already an active transaction in the ALS store. Let me find theconsumeVerificationValuefunction to see how it uses thisAssistant
Let me look at the internal-adapter.ts and the magic-link plugin to understand the flow
Assistant
Let me find the
consumeVerificationValuefunction in this file.Assistant
Let me look at the
consumeVerificationValuefunction.Assistant
Let me see the rest of this function.
Assistant
Now let me look at the magic-link plugin to see where the nesting happens:
Assistant
Let me find the verification endpoint:
Assistant
Let me look at the verify endpoint code.
Assistant
Let me see the rest of the verify endpoint:
Assistant
Let me check
consumeOneWithHooksto see if it callsrunWithTransactiontoo:Assistant
Let me find
consumeOneWithHooks:Assistant
Let me look at the
consumeOneWithHooksfunction:Assistant
Let me check if
createAuthEndpointwraps handlers in a transaction somewhere:Assistant
Let me look at line 124 in internal-adapter.ts:
Assistant
Let me look at line 124 in internal-adapter.ts:
Assistant
Let me look at line 124:
Assistant
Let me check if
createAuthEndpointwraps handlers inrunWithTransaction:Assistant
Let me look at
createSessionin the internal-adapter:Assistant
Let me look at create
Assistant
Let me look more carefully at how the magic-link verify path could cause nesting. Let me check the sign-up route which also uses
runWithTransaction:Assistant
Let me see the
runWithTransactioncall in sign-up:Assistant
Let me look at the adapter interface to understand
consumeOneAssistant
Let me look at the adapter types:
Assistant
Let me look for
consumeOnein the adapter types to understand its contract:Assistant
Let me look at
reserveVerificationValue:Assistant
Let me go back to internal-adapter.ts to see `reserveVerificationValue
Assistant
Let me check if
createAuthEndpointor any handler wrapper wraps in a transaction:Assistant
Now I understand the issue well enough. The
runWithTransactionfunction inpackages/core/src/context/transaction.tsalways opens a newadapter.transaction()without checking if there's already an active transaction in the AsyncLocalStorage. This causes deadlocks when called from within an existing transaction context, since it tries to acquire a second database connection.The fix is to make
runWithTransactionreentrant: check if there's already an active adapter in the ALS store, and if so, simply runfnwithin that existing context instead of opening a newadapter.transaction().Let me implement this fix
Assistant
Now let me implement the fix. The
runWithTransactionfunction needs to check if there's already an active transaction in the ALS store, and if so, reuse it instead of opening a new one:Assistant
Let me also check if there are other places that might nest
runWithTransactioncalls. Let me look at the OIDC provider whereconsumeVerificationValueis alsoAssistant
Let me check the type definitions to understand the difference between
DBAdapterandDBTransactionAdapter:Assistant
Let me reconsider the implementation. When the store already exists (we're inside a transaction), we should just run
fndirectly without creating a new ALS context, since the context is already set up with the correct transaction adapter. Let me simplifyAssistant
Good, now let me verify the full file looks correct:
Assistant
Now let me run the tests related to this change. First, let me find relevant test files
Assistant
Let me run the relevant tests to make sure the changes don't break anything
Assistant
The core tests pass (the 3 failing are pre-existing package resolution issues). Let me run the better-auth package
Assistant
The packages need to be built first. Let me build them.
Assistant
Let me try a more targeted build approach
Assistant
Let me check the build configuration
Assistant
Let me check if the dist directory exists with pre-built files
Assistant
Let me check the vitest config for the core package
Assistant
Let me also check if there are transaction-specific tests
Assistant
Let me look at the transactions test suite
Assistant
Let me check what test exists for transactions and also look at the existing tests more carefully
Assistant
Let me check how
runWithAdapteris used in the codeAssistant
The implementation looks correct.
runWithAdapteris only exported but not used internally, so the only way a store exists is fromrunWithTransaction. My checkif (store)correctly detects if we're already inside a transaction.Let me verify the core tests still pass with the
Assistant
Same results: 306 pass, 3 pre-existing failures unrelated to my change. Let me verify the diff of my change
Assistant
The diff looks good. The key changes are:
- Check if
storeexists (an active transaction context), and if so, runfndirectly instead of opening a nested transaction - Fixed
let called = truetolet called = falseto matchrunWithAdapter's pattern - this ensures graceful fallback if ALS is unavailable
Let me also verify the file looks correct one more time
- Check if
Assistant
Hmm, the file path seems wrong. Let me check the current directory and file.
Assistant
I'm already in the core package directory. Let me open the correct path
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.