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
I'll start by exploring the repository structure to understand the codebase and locate the relevant files mentioned in the issue.
Assistant
Let me look at the key files mentioned in the issue:
@better-auth/corecontext/transaction.mjs(or.tssince this is TypeScript) -runWithTransactiongetCurrentAdapterfunction- The magicLink plugin code
Let me start by examining the transaction context file.
Assistant
The user is pointing out that my tool call format is incorrect. I need to use the proper bash_terminal function format. Let me fix this.
Assistant
Now I can see the issue clearly. The
runWithTransactionfunction always callsadapter.transaction()without checking if there's already an active transaction in the async storage. Let me also look atgetCurrentAdapterto understand how it works - it does check for an existing store and reuses it.Now let me find the magicLink plugin code and the
consumeVerificationValuefunction:Assistant
Let me look at the magic-link plugin code and the internal adapter:
Assistant
Now let me look at the internal adapter to see
consumeVerificationValue:Assistant
Now I can see the issue clearly. In the
consumeVerificationValuefunction, there's a call torunWithTransaction(adapter, async () => { ... }), and inside that callback, there's another operation that may trigger anotherrunWithTransactioncall.Let me look more closely at the
consumeOneWithHooksfunction and how it might trigger another transaction:Assistant
Now I understand the issue completely. Looking at the code:
-
runWithTransactionin/better-auth/packages/core/src/context/transaction.tsalways callsadapter.transaction()unconditionally, without checking if there's already an active transaction. -
getCurrentAdapterdoes check for an existing transaction in the async storage and reuses it. -
When
consumeVerificationValueis called frommagicLinkVerify:- It calls
runWithTransaction(adapter, async () => { ... })which opens tx1 - Inside, it uses
consumeOneWithHookswhich usesgetCurrentAdapter(adapter)- this correctly reuses tx1 - But if any nested operation also calls
runWithTransaction, it will try to open tx2, causing the deadlock
- It calls
The fix should make
runWithTransactionreentrant by checking if there's already an active transaction in the async storage, similar to howgetCurrentAdapterworks.Let me check if there are any tests related to this:
-
Assistant
Let me look for the
createSessionfunction and trace the full call path:Assistant
That's a lot of code. Let me search for where
createSessionusesrunWithTransactionto understand if that's a potential nesting issue too.Assistant
Now let me look at the exact issue more carefully. The issue describes that the problem occurs when
runWithTransactionis called and there's already an active transaction. The fix should be to makerunWithTransactioncheck if there's already an active transaction and reuse it instead of creating a new one.Let me now create the fix:
Assistant
Now I understand the issue perfectly. The
runWithTransactionfunction always callsadapter.transaction()without checking if there's already an active transaction in the async storage. This causes the deadlock when:consumeVerificationValuecallsrunWithTransactionwhich opens tx1- Inside that, another
runWithTransactionis called (either directly or indirectly) which tries to open tx2 - Since there's only one connection in the pool, tx2 blocks waiting for a connection
The fix is to check if there's already an active transaction context and reuse it. Let me implement the fix:
Assistant
Now let me apply this fix to the actual file:
Assistant
Now let me verify the change was applied correctly:
Assistant
The diff shows the changes were applied correctly - we added the check for an existing transaction context and the early return path that reuses the existing transaction.
Now let me create a test script to verify the fix works. First, let me explore the test structure:
Assistant
Let me check if there are any existing tests for the transaction functionality:
Assistant
No existing tests for
runWithTransaction. Let me check the test setup and create a simple test to verify my fix:Assistant
Let me look at how tests are structured in this repo:
Assistant
Let me create a test to verify the fix. First, let me understand the adapter interface:
Assistant
Let me create a simple test to verify the fix works correctly:
Assistant
Now let me check the vitest config and run the test:
Assistant
Let me copy the test file to the proper location and run it:
Assistant
I need to fix the import paths:
Assistant
The test can't run because of module resolution issues. Let me look at how existing tests handle this:
Assistant
Let me look at how the global context is initialized and run a simpler test:
Assistant
Let me check if there's an existing test setup or if I need to build first:
Assistant
Let me try running the existing tests in the better-auth package which uses the magic-link plugin:
Assistant
Let me run the existing magic-link tests to make sure my fix doesn't break them:
Assistant
The tests are having some package resolution issues. Let me try a different approach - I'll verify my fix is correct by examining the code logic more carefully, and then run the full test suite if possible.
Let me also verify the original file to ensure my change is correct:
Assistant
The fix looks correct. Let me verify the diff one more time:
Assistant
The fix is correct. Now let me remove the test file I created (since I shouldn't add tests) and clean up:
Assistant
Now let me try to build the project and run the tests to verify the fix doesn't break anything:
Assistant
The project uses pnpm with catalog protocol. Let me try with pnpm:
Assistant
The pnpm install is taking too long. Let me check if the dependencies are already installed:
Assistant
Dependencies seem to be installed. Let me check if there's a way to run tests in the core package:
Assistant
ttempt to run the existing tests in the core package
Assistant
Let me try with a shorter test that doesn't require full module resolution:
Assistant
All tests pass. The fix logic is correct. Now let me also verify that the original (broken) behavior would have failed:
Assistant
The tests confirm that:
- The old behavior opened nested transactions (2 transaction calls with depth 2)
- The new behavior reuses the existing transaction (1 transaction call with depth 1)
Now let me verify the fix is complete by checking the git diff:
Assistant
I have successfully resolved the issue. Let me provide a summary of what was done:
Summary
Issue
The
magic-linkplugin verification was deadlocking when using database adapters with limited connection pools. The root cause was inrunWithTransactionin@better-auth/core/context/transaction.ts- it always calledadapter.transaction()unconditionally, without checking if a transaction was already active in the async context storage.Root Cause
When
consumeVerificationValue(called during magic link verification) invokedrunWithTransaction, it opened transaction tx1. Inside that transaction, any nested call torunWithTransactionwould try to open tx2, which tried to acquire a second database connection. With a single-connection pool, this caused a deadlock because tx2 blocked waiting for the connection that tx1 was already holding.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.