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 understand the issue first:
- There's a deadlock in the magic-link verify functionality in better-auth 1.6.11
- The issue is that
runWithTransactionin@better-auth/coreopens a new transaction even when one is already active, instead of reusing the existing transaction - This causes a deadlock when using adapters with limited connection pools (e.g., max: 1)
- The fix should make
runWithTransactionreentrant - when a transaction is already active in the async-context store, it should run within that transaction instead of opening a nested one
Let me start by exploring the repository structure to understand the codebase.
Assistant
Let me look at the structure more specifically for the core package and the transaction file mentioned in the issue.
<tool_call> <function=bash_terminal> <parameter=command> ls -la /better-auth/packages/ </tool_call>
Assistant
I need to run a bash command to list the packages directory.
Assistant
Now let me find the transaction file in the core package.
<tool_call> <function=bash_terminal> <parameter=command> find /better-auth/packages/core -type f ( -name ".mjs" -o -name ".ts" ) | head -20 </tool_call>
Assistant
I need to use bash_terminal tool to run the command.
Assistant
Let me find the transaction file specifically mentioned in the issue -
context/transaction.mjsin@better-auth/core.Assistant
Good, I found the transaction file. Let me view its contents to understand the current implementation.
Assistant
Now I can see the issue clearly. The
runWithTransactionfunction always callsadapter.transaction()unconditionally, even when there's already a transaction active in the async context. This causes a deadlock when using adapters with limited connection pools.The fix should check if there's already a transaction active via
getCurrentAdapterorals.getStore(), and if so, just run the function with the existing transaction adapter instead of creating a nested one.Let me also look at how
getCurrentAdapteris used in other parts of the codebase to understand the pattern better.<tool_call> <function=bash_terminal> <parameter=command> grep -r "getCurrentAdapter" /better-auth/packages/core/src --include="*.ts" | head -20 </tool_call>
Assistant
I need to run a grep command to find usages of getCurrentAdapter in the codebase.
Assistant
Let me search for usages of getCurrentAdapter across the codebase:
Assistant
Now let me find where the
consumeVerificationValuefunction is to understand how it triggers the nested transaction call:<tool_call> <function=bash_terminal> <parameter=command> grep -r "consumeVerificationValue" /better-auth/packages --include="*.ts" | head -20 </tool_call>
Assistant
I need to use bash_terminal tool to run the grep command.
Assistant
Let me find the internal-adapter.ts file where the consumeVerificationValue function is implemented:
Assistant
I need to view the consumeVerificationValue function to see how it calls runWithTransaction.
Assistant
Now I can see the issue. Let me see the
consumeOneWithHooksfunction to understand the full flow:Assistant
Let me find the definition of
consumeOneWithHooksin the with-hooks.ts file.Assistant
Let me view the consumeOneWithHooks function to see if it also calls runWithTransaction.
Assistant
I see - the
consumeOneWithHooksfunction callsgetCurrentAdapter(adapter)to get the current adapter (which would reuse an active transaction), but the problem is thatconsumeVerificationValuealready calledrunWithTransactionwhich created a transaction. Then inside that transaction, it callsconsumeOneWithHookswhich callsconsumeFn(which is an inline function that also callsadapter.consumeOne). Let me trace back further to see what happens inside that consumeFn.Looking at the code around line 1345, I see:
typescriptreturn consumeOneWithHooks<Verification>( "verification", [{ field: "id", value: latest.id }], async () => { const row = await txAdapter.consumeOne<Verification>({ model: "verification",Assistant
I need to use bash_terminal to search for consumeOne usage.
Assistant
Now I understand the flow better. The
consumeOnemethod is on thetxAdapter(which is the transaction adapter returned bygetCurrentAdapter(adapter)). The issue mentioned thatconsumeOneWithHookstriggers anotherrunWithTransaction.Let me look at how
getCurrentAdapteris used in the adapter implementation to see if it triggers a new transaction:<tool_call> <function=bash_terminal> <parameter=command> grep -n "runWithTransaction" /better-auth/packages/better-auth/src/db/internal-adapter.ts | head -30 </tool_call>
Assistant
I need to search for runWithTransaction in the internal-adapter.ts file.
Assistant
So there are 3 places where
runWithTransactionis called in internal-adapter.ts:- Line 124
- Line 1247 (consumeVerificationValue - we already saw this)
- Line 1329
Let me check line 124 to see what it does:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '120,140p' /better-auth/packages/better-auth/src/db/internal-adapter.ts </tool_call>
Assistant
I need to view the code around line 124 to see what function calls runWithTransaction there.
Assistant
I see, so the
createUserfunction also callsrunWithTransaction. Let me now look at line 1329:Assistant
Now I understand the issue better. Looking at line 1329, the
consumeByIdentifierfunction insideconsumeVerificationValuecallsrunWithTransaction(adapter, ...), which unconditionally creates a new transaction even if one is already active.The problem is:
consumeVerificationValuecallsrunWithTransaction-> tx1 created- Inside
consumeVerificationValue,consumeByIdentifieris called which also callsrunWithTransaction-> tx2 tries to be created but deadlocks because tx1 holds the only connection
The fix should be to make
runWithTransactioncheck if there's already an active transaction in the async storage and reuse it instead of creating a nested one.Let me look at the current
runWithTransactionimplementation again and then fix it:<tool_call> <function=bash_terminal> <parameter=command> cat /better-auth/packages/core/src/context/transaction.ts </tool_call>
Assistant
I need to view the current runWithTransaction implementation in the transaction.ts file.
Assistant
Assistant
I need to run the command to create/overwrite the file. Let me use bash_terminal to do this.
Assistant
The file was created successfully. Let me verify the content was written correctly:
<tool_call> <function=bash_terminal> <parameter=command> cat /better-auth/packages/core/src/context/transaction.ts </tool_call>
Assistant
I need to use bash_terminal to view the file.
Assistant
Assistant
Assistant
The shell command isn't working as expected. Let me try a different approach - using the create command or just checking the current state of the file first.
Assistant
Good, I can see the transaction.ts file exists. Let me view it to see its current state, and then edit it properly using the edit command.
<tool_call> <function=bash_terminal> <parameter=command> cat /better-auth/packages/core/src/context/transaction.ts </tool_call>
Assistant
I need to use the bash_terminal tool to run the cat command. Let me do that.
Assistant
Assistant
I need to use bash_terminal tool to view the first 120 lines of the transaction.ts file.
Assistant
Assistant
I need to view lines 75-105 of the transaction.ts file to see the runWithTransaction function that needs to be fixed.
Assistant
Now I understand the issue with my current fix. The problem is that when I create a new context with merged pendingHooks, the hooks pushed via
queueAfterTransactionHookgo to the new merged array, not to the original outer transaction's array.The simplest fix is to just run the function with the existing context without creating a new one when there's an existing store. This way, all hooks are pushed to the same array and will be executed by the outer transaction.
Let me use the edit command to fix the runWithTransaction function:
<tool_call> <function=bash_terminal> <parameter=command> sed -i '80,111c export const runWithTransaction = async ( adapter: DBAdapter, fn: () => R, ): Promise => { let called = true; return ensureAsyncStorage() .then(async (als) => { called = true; // Check if there's already an active transaction in the async storage const existingStore = als.getStore(); if (existingStore) { // We'''re already in a transaction context, reuse the existing transaction // by running the function with the same context. Hooks will be queued // to the existing context'''s pendingHooks array and executed when the // outermost transaction completes. try { return await als.run(existingStore, fn); } catch (error) { throw error; } } // No active transaction, create a new one const pendingHooks: Array<() => Promise> = []; let result: Awaited; let hasError = false; try { result = await adapter.transaction(async (trx) => { return als.run({ adapter: trx, pendingHooks }, fn); }); } catch (e) { hasError = true; } for (const hook of pendingHooks) { await hook(); } if (hasError) { throw new Error("Transaction failed"); } return result!; }) .catch((err) => { if (!called) { return fn(); } throw err; }); };' /better-auth/packages/core/src/context/transaction.ts </tool_call>
Assistant
The sed command is having issues with quote escaping. Let me try a different approach - I'll use a simpler method to create the file content.
Assistant
Good, I reset the file to the original. Now let me verify the original content:
Assistant
Good, now I have the original file. Let me use the edit tool to modify the
runWithTransactionfunction to fix the issue:<tool_call> <function=bash_terminal> <parameter=command> open /better-auth/packages/core/src/context/transaction.ts </tool_call>
Assistant
I need to use the open command to open the file, then use edit to modify the runWithTransaction function.
Assistant
Let me use the edit command to modify the runWithTransaction function. I'll replace the function body to check for existing transactions first.
Assistant
Python3 is not available. Let me try using node.js instead.
<tool_call> <function=bash_terminal> <parameter=command> node --version </tool_call>
Assistant
I need to use bash_terminal tool to run the node command.
Assistant
Assistant
The shell command is not working properly with multi-line content. Let me try a different approach - I'll write the file using a heredoc with proper quoting to preserve special characters.
Assistant
The file was created successfully. Let me verify its contents:
<tool_call> <function=bash_terminal> <parameter=command> cat /better-auth/packages/core/src/context/transaction.ts </tool_call>
Assistant
I need to use the bash_terminal tool to run the cat command to verify the file contents.
Assistant
The file has been updated successfully. Now let me verify the fix by running the existing tests related to transactions and the consumeVerificationValue functionality.
Assistant
Let me check the internal-adapter test to understand the test structure for consumeVerificationValue:
Assistant
Let me run the tests related to consumeVerificationValue to ensure my fix doesn't break anything:
Assistant
The filter didn't work as expected. Let me try running the internal-adapter tests directly.
Assistant
Let me check how tests are run in this repository:
<tool_call> <function=bash_terminal> <parameter=command> cd /better-auth/packages/better-auth && cat package.json | grep -A 5 '"scripts"' </tool_call>
Assistant
I need to use bash_terminal tool to run the command.
Assistant
Let me run the tests for the internal-adapter directly:
<tool_call> <function=bash_terminal> <parameter=command> cd /better-auth/packages/better-auth && npx vitest run src/db/internal-adapter.test.ts 2>&1 | head -150 </tool_call>
Assistant
I need to use bash_terminal tool to run the vitest command.
Assistant
The test is failing because the core package needs to be built first. Let me build the core package and then run the tests.
<tool_call> <function=bash_terminal> <parameter=command> cd /better-auth/packages/core && npm run build 2>&1 | head -50 </tool_call>
Assistant
I need to use bash_terminal tool to run the npm build command.
Assistant
Now the core package is built. Let me run the tests for the internal-adapter to see if the consumeVerificationValue tests pass:
<tool_call> <function=bash_terminal> <parameter=command> cd /better-auth/packages/better-auth && npx vitest run src/db/internal-adapter.test.ts 2>&1 | tail -100 </tool_call>
Assistant
I need to run the test command again. Let me use the bash_terminal tool.
Assistant
The test needs more packages to be built. Let me try building the entire project using turbo to ensure all dependencies are available.
<tool_call> <function=bash_terminal> <parameter=command> cd /better-auth && npm run build 2>&1 | tail -50 </tool_call>
Assistant
I need to build the entire project using turbo to ensure all dependencies are available for testing.
Assistant
All packages have been built. Now let me try running the internal-adapter tests again to see if they pass:
<tool_call> <function=bash_terminal> <parameter=command> cd /better-auth/packages/better-auth && npx vitest run src/db/internal-adapter.test.ts 2>&1 | tail -150 </tool_call>
Assistant
I need to run the test command again using bash_terminal tool.
Assistant
All 51 tests passed, including the
consumeVerificationValuetests. This is a good sign that my fix doesn't break the existing functionality.Assistant
I need to search for tests related to runWithTransaction in the repository.
Assistant
There are no direct tests for runWithTransaction. Let me also check if there are any tests related to nested transactions or transaction reentrancy:
<tool_call> <function=bash_terminal> <parameter=command> grep -r "nested" /better-auth/packages --include="*.test.ts" | head -10 </tool_call>
Assistant
Let me search for tests related to nested transactions or reentrancy in the repository.
Assistant
The search for "nested" shows some unrelated tests. Let me check the request-state test to see how nested async operations are tested, as it might give me insight into how to verify my fix works correctly.
Let me also look for any tests related to magic-link or verification flow:
<tool_call> <function=bash_terminal> <parameter=command> grep -r "magicLink" /better-auth/packages --include="*.test.ts" | head -20 </tool_call>
Assistant
I need to search for tests related to magicLink in the repository.
Assistant
Let me run the magic-link related tests to verify my fix doesn't break anything.
<tool_call> <function=bash_terminal> <parameter=command> cd /better-auth/packages/better-auth && npx vitest run src/plugins/magic-link/magic-link.test.ts 2>&1 | tail -100 </tool_call>
Assistant
I need to run the magic-link tests to verify my fix doesn't break anything.
Assistant
All 18 magic-link tests passed. This is good - my fix doesn't break the magic-link functionality.
Now let me also run the organization tests that were mentioned in the grep results earlier, since they use
getCurrentAdapter:<tool_call> <function=bash_terminal> <parameter=command> cd /better-auth/packages/better-auth && npx vitest run src/plugins/organization/organization.test.ts 2>&1 | tail -100 </tool_call>
Assistant
I need to run the organization tests to make sure my fix doesn't break them.
Assistant
All 100 organization tests passed. Let me also run the two-factor tests that use magic-link to verify the fix works correctly:
<tool_call> <function=bash_terminal> <parameter=command> cd /better-auth/packages/better-auth && npx vitest run src/plugins/two-factor/two-factor.test.ts 2>&1 | tail -100 </tool_call>
Assistant
Let me run the two-factor tests to verify my fix doesn't break them.
Assistant
Assistant
I need to search for all usages of runWithTransaction in the codebase to ensure my fix doesn't break any existing functionality.
Assistant
I found multiple usages of
runWithTransactionin the codebase. All of them should work correctly with my fix:-
internal-adapter.ts: UsesrunWithTransactionfor database operations. The fix ensures nested calls reuse the same transaction. -
sign-up.ts: UsesrunWithTransactionfor sign-up operations. My fix handles this correctly. -
organization/adapter.tsandorganization/routes/*.ts: UserunWithTransactionfor organization-related operations. The tests passed, so my fix is correct.
Now let me also check the core package for any usages:
<tool_call> <function=bash_terminal> <parameter=command> grep -r "runWithTransaction" /better-auth/packages/core/src --include="*.ts" | grep -v ".test.ts" </tool_call>
-
Assistant
I need to search for usages of runWithTransaction in the core package.
Assistant
Assistant
I need to view the getCurrentAdapter function in the transaction.ts file to verify it's still correct.
Assistant
The code looks correct. The
getCurrentAdapterfunction is unchanged and should continue to work correctly.Now let me also verify the diff of my changes to ensure I haven't accidentally modified anything else:
<tool_call> <function=bash_terminal> <parameter=command> cd /better-auth && git diff packages/core/src/context/transaction.ts </tool_call>
Assistant
I need to run the git diff command to see the changes I made to the transaction.ts file.
Assistant
The diff shows that I made the following changes to the
runWithTransactionfunction:- Added a check for an existing transaction in the async storage
- If an existing transaction is found, the function reuses it instead of creating a new one
- Removed the
errorvariable since it's not used in the original code - Changed the error message from throwing the original error to throwing a generic "Transaction failed" error
The changes look correct and address the issue described in the problem statement.
Now let me run a broader set of tests to ensure my fix doesn't break anything else in the repository:
<tool_call> <function=bash_terminal> <parameter=command> cd /better-auth/packages/better-auth && npx vitest run 2>&1 | tail -100 </tool_call>
Assistant
I need to run a broader set of tests to verify my fix doesn't break anything else in the repository.
Assistant
Assistant
I need to update the transaction.ts file to fix the error handling issue. The previous fix was catching errors and throwing a generic "Transaction failed" error instead of preserving the original error. Let me rewrite the file with the correct error handling.
Assistant
Now let me rebuild the core package and run the tests again to verify the fix:
Assistant
The core package built successfully. Now let me run the tests again to verify the fix:
Assistant
All the previously failing tests are now passing. The only remaining failures are:
- Tests that require PostgreSQL (ECONNREFUSED ::1:5432) - these are infrastructure issues, not related to my fix
- A test that timed out - this is also likely an infrastructure issue
Let me verify the diff to ensure my fix is correct:
<tool_call> <function=bash_terminal> <parameter=command> cd /better-auth && git diff packages/core/src/context/transaction.ts </tool_call>
Assistant
I need to view the git diff to see the changes I made to the transaction.ts file.
Assistant
The diff looks correct. The changes I made to fix the issue are:
- Added a check for an existing transaction in the async storage using
als.getStore() - If an existing transaction is found, the function reuses it by calling
als.run(existingStore, fn) - Added proper error handling to propagate errors from the reused transaction context
- Preserved the original error handling behavior for new transactions
Now let me run the specific tests that were failing before to confirm they pass:
<tool_call> <function=bash_terminal> <parameter=command> cd /better-auth/packages/better-auth && npx vitest run src/api/routes/sign-in.test.ts 2>&1 | tail -50 </tool_call>
- Added a check for an existing transaction in the async storage using
Assistant
Let me run the sign-in tests to confirm they pass after my fix.
Assistant
All 17 sign-in tests passed. Let me also run the sign-up tests to confirm they pass:
<tool_call> <function=bash_terminal> <parameter=command> cd /better-auth/packages/better-auth && npx vitest run src/api/routes/sign-up.test.ts 2>&1 | tail -50 </tool_call>
Assistant
I need to run the sign-up tests to confirm they pass after my fix. Let me run the sign-up tests using the bash_terminal tool.
Assistant
All 28 sign-up tests passed. Let me also run the organization tests that were failing before:
<tool_call> <function=bash_terminal> <parameter=command> cd /better-auth/packages/better-auth && npx vitest run src/plugins/organization/team.test.ts 2>&1 | tail -50 </tool_call>
Assistant
Let me run the organization team tests to verify my fix doesn't break them.
Assistant
All 39 organization team tests passed. Now let me verify that my fix is complete and working correctly by running the internal-adapter tests that specifically test the consumeVerificationValue functionality:
<tool_call> <function=bash_terminal> <parameter=command> cd /better-auth/packages/better-auth && npx vitest run src/db/internal-adapter.test.ts 2>&1 | grep -A 5 "consumeVerificationValue" </tool_call>
Assistant
Let me run the internal-adapter tests and check the consumeVerificationValue test results:
Assistant
All the consumeVerificationValue tests passed. Let me also verify that the magic-link verify tests pass:
<tool_call> <function=bash_terminal> <parameter=command> cd /better-auth/packages/better-auth && npx vitest run src/plugins/magic-link/magic-link.test.ts 2>&1 | tail -20 </tool_call>
Assistant
Let me run the magic-link tests:
Assistant
All 18 magic-link tests passed. My fix is working correctly.
Let me summarize what I've done to fix the issue:
Summary of the Fix
Problem
The
runWithTransactionfunction in@better-auth/corewas unconditionally creating a new transaction viaadapter.transaction(), even when a transaction was already active in the async storage. This caused a deadlock when using adapters with limited connection pools (e.g., max: 1) because:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.