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 exploring the repository structure to understand the codebase.
Assistant
Now let me look at the
consumeVerificationValuefunction and related code.Assistant
Now let me understand the full picture. Let me look at
consumeOneWithHooksto understand the nestedrunWithTransactioncall.Assistant
Let me look at the
consumeOnemethod to understand if it also opens a transaction:Assistant
Let me look at the
runWithAdapterfunction and understand the difference betweenrunWithTransactionandrunWithAdapter:Assistant
Let me check if there are any tests for the transaction module:
Assistant
There's no specific test file for
transaction.ts. Let me look at the existing tests tosee how to test transactions:Assistant
Now let me look at how the Kysely adapter handles transactions:
Assistant
Now let me understand the architecture. Let me also look at the drizzle adapter to see how it handles transactions:
Assistant
Let me also look at the factory test for
consumeOne:Assistant
Now let me check the package structure to understand the test setup:
Assistant
Let me check
__getBetterAuthGlobal:Assistant
Now let me write a quick reproduction script to verify the issue:
Assistant
I've reproduced the deadlock. Now let me apply the fix to
runWithTransactioninpackages/core/src/context/transaction.ts:Assistant
Let me check if kysely adapter implements
consumeOne:Assistant
Let me look at where else
runWithTransactionis called:Assistant
Let me look at the magic-link verify path:
Assistant
Let me look at the factory.ts more carefully to understand how the
adapterreference is closed over:Assistant
Now I have enough understanding to implement the fix. Let me apply the fix to
runWithTransaction:Assistant
Let me write a test script that uses the fixed code:
Assistant
Now I need to also fix the
consumeOnefallback in factory.ts which directly callsadapter.transactionwithout checking if we're already in one:Assistant
Let me check imports in factory.ts:
Assistant
Let me check if there's a circular dependency issue:
Assistant
Let me check if there are circular dependencies:
Assistant
The
context/transaction.tsonly has type imports fromdb/adapter, so there's no circular dependency. Let me verify by trying to usegetCurrentAdapterin factory.ts:Assistant
Let me look at the consumeOne code more carefully to understand the structure:
Assistant
Now let me see the imports more carefully:
Assistant
Let me first check that adding an import to factory.ts would not cause any issues:
Assistant
Let me search for any tests in the @zenstackhq package or look for how the consume path is hit:
Assistant
Let me look at the factory.ts more carefully to plan the fix for consumeOne and incrementOne:
Assistant
Now let me look at the
getCurrentAdaptersignature and understand its semantics:Assistant
Let me look at the DBAdapter type to confirm:
Assistant
Let me check if there are any actual runtime imports from factory.ts to context, or vice versa:
Assistant
Let me also verify that the consumeOne fallback works correctly. Let me trace through the issue more carefully:
consumeVerificationValuecallsrunWithTransaction(adapter, ...)- opens tx1, runs fn1.- In fn1,
consumeOneWithHooksis called. consumeOneWithHookscallsconsumeFnwhich callstxAdapter.consumeOne(...).txAdapter.consumeOne(...)is the factory's consumeOne. If no native impl, falls back toadapter.transaction(...)- this is where the deadlock happens.
So the fix to
runWithTransactionalone doesn't fix theconsumeOnefallback. We need to also fix the factory.Let me make the factory.ts fix now. Let me look at the full file structure:
Assistant
Let me check if importing
runWithTransactionwould cause a circular dependency:Assistant
The test command is timing out. Let me try a more targeted approach - just running the test files for the changes I'mmaking:
Assistant
Let me try running the existingfactory.test.ts:
Assistant
The tests can't run because the package isn't built. Let me try building it:
Assistant
Now let me run the existing tests to verify they pass:
Assistant
Let me run all the tests in the core package to make sure I haven't broken anything:
Assistant
All 322 tests pass. Now let me also fix the
consumeOnefallback in factory.ts:Assistant
Now let me look at theimport section to understand how to add the new import:
Assistant
Let me check
db/adapter/index.ts:Assistant
Let me verify there are no circular dependencies by adding the import:
Assistant
Now I'll make the change to factory.ts to use the existing transaction when in one:
Assistant
Let me only add the import and not modify the rest:
Assistant
Now let me find and update the consumeOne fallback:
Assistant
Now let me update the consumeOne fallback:
Assistant
I see, my edit ended up duplicating the
res = await withSpan(line. Let me fix this:Assistant
Let me fix the indentation:
Assistant
Let me revert this and apply the change more carefully:
Assistant
Now let me look at the incrementOne fallback to fix it too:
Assistant
Now let me also fix the incrementOne fallback:
Assistant
I see the issue - my edit replaced the original
if (adapterInstance.incrementOne)block too. Let me look at the current state and fix:Assistant
The structure is broken. Let me look at the entire
incrementOnemethod and fix it properly:Assistant
The structure is broken. Let me revert all my changes to factory.ts and start over with a cleaner approach:
Assistant
Good, the file is now reset to original. Let me now make the changes more carefully using sed:
Assistant
Now let me make the change to consumeOne fallback using replace:
Assistant
Let me use a Python script to do the replacement precisely:
Assistant
Let me use a script file approach instead:
Assistant
Let me verify the incrementOne fallback:
Assistant
Let me verify the imports are correct:
Assistant
Now let me build the package and run the tests to make sure everything works:
Assistant
Let me verify the fix with my reproduction script:
Assistant
Now let me write a more comprehensive test that simulates the actual scenario from the issue:
Assistant
Let me also verify against the actual built file:
Assistant
Now let me run the better-auth tests to see if anything broke:
Assistant
Let me build the kysely-adapter package first:
Assistant
Let me build all the packages:
Assistant
All 51 tests pass. Let me also run the magic-link tests:
Assistant
All 18 magic-link tests pass. Let me also run other related tests:
Assistant
The failures are environment issues (no Postgres connection, mongo-adapter not built), not related to my fix. Let me build the mongo-adapter and try again:
Assistant
Let me look at this test to see if it's related to my change:
Assistant
Let me look at what test produces the timeout:
Assistant
Let me verify the failing tests are unrelated to my fix by checking git history:
Assistant
These test failures are pre-existing and unrelated to my fix. Let me restore my changes:
Assistant
Good, my changes are restored. Let me check git diff:
Assistant
Let me also run the related tests to make sure everything still passes:
Assistant
Let me rebuild the core package to make sure the build is up-to-date:
Assistant
Let me also check the drizzle-adapter tests:
Assistant
All tests pass. Now let me also check the organization tests, since the issue mentions organizationplugin:
Assistant
All 100 organization tests pass. Let me also run a wider set of tests:
Assistant
Let me also check the magic-link verify tests more specifically:
Assistant
Let me write a temporary script to verify the fix with a more thorough test, simulating the actual deadlock scenario:
Assistant
Let me adjust the test to be more realistic. The test was actually showing the expected serialization behavior, not the deadlock:
Assistant
The test demonstrates that:
- With my fix:
consumeVerificationValuecompletes successfully (0ms) even withMAX_CONNECTIONS = 1. - Without my fix (broken version): nested
runWithTransactioncalls deadlock.
Now let me clean up the temporary scripts and do a final check:
- With my fix:
Assistant
Let me make sure the fix is comprehensive by checking edge cases. Let me look at the final state of the files:
Assistant
Let me verify the fix with the actual built files by running a test through the actual exported modules:
Assistant
Let me also verify the factory.ts fix is built correctly:
Assistant
The fix is correctly built intothe dist file. Let me also check that getCurrentAdapter is imported in the built file:
Assistant
Let me now run the magic-link tests one more time with the latest build:
Assistant
All tests pass. Let me do a final summary of my changes:
Summary of changes
The issue describes a deadlock in magic-link verification that occurs when:
runWithTransactionis called and opens a transaction (tx1), taking a connection from the pool.- Inside tx1, another
runWithTransactioncall is triggered (e.g., throughconsumeOnefallback), which tries to open tx2. - tx2 needs a second connection but the pool is limited to one, so it deadlocks.
The fix consists of two parts:
Part 1:
packages/core/src/context/transaction.tsMade
runWithTransactionreentrant. When an adapter/transaction is already active in the async-context store, runfnwithin it instead of opening a nestedadapter.transaction. This mirrors the existing behavior ofgetCurrentAdapter.Part 2:
packages/core/src/db/adapter/factory.tsMade the
consumeOneandincrementOnefallback paths also check for an active transaction and reuse it. Without this fix, the fallback path would still calladapter.transaction(...)directly even if already in a transaction.Let me do a final verification by running the full set of tests:
Assistant
Now let me go through the checklist:
Checklist:
-
If an error was reported in the issue description, I have successfully reproduced it.
- ✅ I created reproduction scripts ( and ) that confirmed the deadlock scenario:
-
Assistant
The diff looks clean and focused. Let me submit the changes.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.