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 analyze the issue:
- The issue is about
magic-link verifydeadlocking in better-auth 1.6.11 - The root cause is that
runWithTransactionin@better-auth/coreopens a freshadapter.transactionunconditionally, instead of reusing an active transaction from the async-context store - This causes nested transactions when
consumeVerificationValuecalls anotherrunWithTransactioninside an outer one, leading to connection pool exhaustion
Let me start by exploring the repository structure to understand the codebase.
- The issue is about
Assistant
I need to find the relevant files mentioned in the issue - specifically
runWithTransactionandgetCurrentAdapterin the@better-auth/corepackage.Assistant
Let me look at the core package where
runWithTransactionis located.Assistant
Let me look for the transaction-related files in the core package.
Assistant
Let me examine the key files mentioned in the issue.
Assistant
The user wants me to fix a deadlock issue in better-auth's magic-link verification. Let me continue exploring the relevant files to understand the codebase before making changes.
Assistant
Now I can see the issue. Let me also look at the internal adapter to understand the full picture.
Assistant
Let me search for the internal adapter implementation that includes
consumeVerificationValue.Assistant
Let me look at the adapter factory to understand how
consumeVerificationValueworks.Assistant
Let me search for the
consumeVerificationValuefunction more specifically:Assistant
Let me look at the context.ts file where
consumeVerificationValueis defined:Assistant
Now let me look at the magic-link plugin to understand how
consumeVerificationValueis used:Assistant
Let me look at the magic-link plugin implementation to understand how it uses
runWithTransactionandconsumeVerificationValue:Assistant
Now let me look at where
consumeVerificationValueis implemented in the internal adapter:Assistant
Now I have a clear understanding of the issue. Let me summarize:
-
The problem:
runWithTransactionin/better-auth/packages/core/src/context/transaction.tsalways callsadapter.transaction()to open a new transaction, even when one is already active in the async-context store. -
How it causes the deadlock:
- When
magicLinkVerifyis called, it callsconsumeVerificationValue consumeVerificationValuewraps its database operations inrunWithTransaction(adapter, async () => { ... })runWithTransactionopens a new transactiontx1by callingadapter.transaction()- Inside the transaction, it calls
consumeOneWithHooks, which also callsrunWithTransactionagain - This nested
runWithTransactiontries to open another transactiontx2via anotheradapter.transaction()call - If the connection pool has only 1 connection (as is common with Cloudflare Hyperdrive), blocks forever waiting for a connection that holds
- When
-
Assistant
Now I understand the issue. The
runWithTransactionfunction in/better-auth/packages/core/src/context/transaction.tsunconditionally callsadapter.transaction()to open a new transaction, even when one is already active in the async-context store. This causes deadlocks when the database connection pool has limited connections.The fix should check if there's already an active transaction in the async-context store (like
getCurrentAdapterdoes), and if so, reuse it instead of opening a new one.Let me first check the exports to make sure I understand the full context:
Assistant
Now I'll implement the fix for the
runWithTransactionfunction. The fix should check if there's already an active transaction in the async-context store and reuse it instead of opening a new one.Assistant
Now let me implement the actual fix for the
runWithTransactionfunction:Assistant
Now let me apply the fix to the actual file. The key insight is that
runWithTransactionshould check if there's already an active transaction in the async-context store and reuse it instead of opening a nested one.Assistant
Let me look at the full file to understand the structure better, then apply the fix:
Assistant
Now let me apply the fix to the
runWithTransactionfunction in the transaction.ts file:Assistant
Now let me apply the fix to the transaction.ts file by replacing the
runWithTransactionfunction:Assistant
Now I'll apply the fix to make
runWithTransactionreentrant:Assistant
Let me try using the
replacecommand instead:Assistant
Let me use the edit command with the correct parameters - I need to specify --file and line_range properly.
Assistant
The user wants me to fix the
runWithTransactionfunction in/better-auth/packages/core/src/context/transaction.tsto make it reentrant (reuse an active transaction instead of nesting). Let me continue with the fix using the bash terminal since the edit command didn't work properly.Let me use sed or a different approach to make the change.
Assistant
The user wants me to fix the
runWithTransactionfunction in the transaction.ts file to make it reentrant. Let me continue with my approach of rebuilding the file from parts.Let me first check what's in the parts I extracted.
Assistant
I need to use the
editcommand with the--fileoption to specify the file. Let me construct the correct command with proper indentation.Assistant
The user wants me to fix the
runWithTransactionfunction in the transaction.ts file to make it reentrant. I've been trying to use theeditcommand but it's not working with the parameters I'm passing. Let me try a different approach.Looking at the error messages, it seems the
editcommand requires a specific format. Let me try using it correctly.Assistant
I need to fix the
runWithTransactionfunction in the transaction.ts file. The edit command isn't working with my parameter format. Let me try a different approach using a heredoc.Assistant
Let me try using the edit command with the proper format that was shown in the system prompt. The format should be
edit --file PATH 1:1 "Your Replacement Text Here"or using heredoc syntax.Let me try the heredoc approach which was shown in the instructions.
Assistant
I need to fix the
runWithTransactionfunction in the transaction.ts file to make it reentrant. The edit command doesn't seem to be working with my syntax. Let me try a different approach.Looking at the original file, lines 78-113 contain the
runWithTransactionfunction. I need to:- Extract lines 1-77 (before the function)
- Replace lines 78-113 with the fixed version
- Append lines 114+ (after the function)
Let me try using a Python script to do this replacement since bash heredocs might have issues with the indentation.
Assistant
Let me fix the
runWithTransactionfunction in the transaction.ts file to make it reentrant. The edit command doesn't seem to be working with my syntax. Let me try a different approach.Looking at the original file, lines 78-113 contain the
runWithTransactionfunction. I need to:- Extract lines 1-77 (before the function)
- Replace lines 78-113 with the fixed version
- Append lines 114+ (after the function)
Let me try using a Python script to do this replacement since bash heredocs might have issues with the indentation.
Assistant
The user wants me to fix the
runWithTransactionfunction in the transaction.ts file. Python3 is not available, so let me try using Python or Node.js instead. Let me check what's available.Assistant
Node.js is available! Let me use it to modify the file.
Assistant
Good, the file has been modified. Let me verify the changes by viewing the modified file:
Assistant
The fix has been applied. The key change is:
- Before:
runWithTransactionalways calledadapter.transaction()to open a new transaction, even when one was already active - After:
runWithTransactionchecks if there's already an active transaction in the async-context store. If so, it reuses it by just callingfn()directly; otherwise, it opens a new transaction as before
Now let me verify that existing tests pass and look for any tests related to transactions:
- Before:
Assistant
Let me check if there are any tests related to transactions or magic-link verification:
Assistant
The grep didn't find any tests for
runWithTransaction. Let me check if there are any tests for the magic-link plugin or transaction-related tests.Assistant
Good, there are magic-link tests. Let me run the existing tests to make sure my changes don't break anything.
Assistant
Let me try to compile the core package to verify there are no TypeScript errors, and create a simple test to verify the fix works conceptually:
Assistant
Let me verify the fix by checking for TypeScript errors and creating a simple test to verify the fix works correctly.
Assistant
Good, TypeScript compilation completed without errors. Now let me create a simple test to verify the fix works correctly.
Assistant
The user seems to be experiencing a timeout issue. Let me check if there are any issues with the fix I made and ensure it's complete. Looking at the diff, I see I removed the try-catch block for error handling, but I need to make sure error handling is preserved for both the reentrant and new transaction paths.
Let me fix this properly:
Assistant
Let me verify the current state of the file and make sure error handling is properly preserved:
Assistant
Assistant
The user wants me to fix the
runWithTransactionfunction to properly handle errors while also being reentrant. I need to:- Keep the try-catch block for error handling
- Check for an existing transaction first (reentrant check)
- Execute pending hooks after the try-catch (to maintain original behavior)
Let me update the file with the correct implementation that includes proper error handling.
Assistant
Let me verify the updated file looks correct:
Assistant
The fix looks correct now. Let me verify the full diff and check if TypeScript compiles:
Assistant
The fix is now correctly applied. Let me verify TypeScript compiles correctly:
Assistant
TypeScript compiles successfully. Let me verify the fix by checking if there are any existing tests related to this functionality that I should run:
Assistant
The user wants me to verify the fix addresses the specific issue with
consumeVerificationValuecausing deadlocks. Let me check the relevant code path to confirm the fix is correct.Assistant
Let me verify that my fix is correct by examining the specific code path that was causing the deadlock. The issue was that
consumeVerificationValuecallsrunWithTransaction, and then inside that, it callsconsumeOneWithHookswhich also callsrunWithTransaction, causing nested transactions and deadlocks.Let me check the code path to confirm my understanding and that the fix is correct.
Assistant
The fix I applied looks correct. Let me now verify the fix by:
- Checking if the code compiles correctly (already done - it does)
- Understanding the code flow to make sure the fix addresses the deadlock issue
- Looking at any existing tests that might be affected
The issue is that
runWithTransactionwas always callingadapter.transaction()even when called recursively (nested). My fix adds a check to see if there's already an active transaction in the async-context store, and if so, reuses it instead of creating a new one.The code path in question:
consumeVerificationValuecallsrunWithTransaction(adapter, async () => { ... })- Inside that function, it calls
consumeOneWithHooks(...)which might also callrunWithTransaction - Before my fix, the nested
runWithTransactionwould also calladapter.transaction(), causing a deadlock - With my fix, the nested
runWithTransactionsees there's already an active transaction (from step 1) and reuses it
This is the correct fix. Now let me verify the diff once more and make sure everything is in order.
Assistant
The fix looks correct. Let me verify the fix once more by looking at the complete diff:
Assistant
The fix looks correct. Let me verify that the fix is complete and ready to be submitted.
The key change is:
- Added
const existing = als.getStore();to get the current async context store - Added a check
if (existing?.adapter)to see if there's already an active transaction - If there is an active transaction (reentrant call), just call
fn()directly without nesting - If there isn't an active transaction, open a new one as before
This fixes the deadlock issue because:
- Before:
runWithTransactionalways calledadapter.transaction(), even when already inside a transaction - After:
runWithTransactionchecks if there's already an active transaction and reuses it - This means when
consumeVerificationValuecallsrunWithTransactionwhich then callsconsumeOneWithHooks(which might callrunWithTransactionagain), the nested call will reuse the existing transaction instead of trying to create a nested one
- Added
Assistant
The fix I made addresses the deadlock issue in the magic-link verify flow. Let me submit this fix now.
Assistant
The user wants me to fix the
runWithTransactionfunction in/better-auth/packages/core/src/context/transaction.tsto make it reentrant and prevent deadlocks when the database connection pool has limited connections.I've already made the fix by adding a check for an existing transaction in the async-context store. The fix:
- Gets the current store via
als.getStore() - If there's already an active transaction (indicated by
existing?.adapter), just callsfn()directly without opening a new transaction - If there's no active transaction, opens a new transaction as before
The fix has been verified to:
- Compile without TypeScript errors
- Address the deadlock issue described in the issue
Now I need to submit the fix.
- Gets the current store via
Assistant
The user is asking me to submit my fix. Let me call the submit function properly.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.