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 explore the repository structure first.
- Assistant
Let me look at the core transaction file:
- Assistant
Now let me find the
consumeVerificationValuefunction: - Assistant
Let me look at the internal-adapter.ts to see the
consumeVerificationValueimplementation: - Assistant
Let me see the
consumeVerificationValuefunction in detail: - Assistant
Now let me look at the
consumeOneWithHooksfunction: - Assistant
Let me find the
consumeOneWithHooksdefinition: - Assistant
Let me look at the with-hooks.ts file to understand
consumeOneWithHooks. - Assistant
Let me look at consumeOneWithHooks implementation:
- Assistant
Let me look at the
consumeOneimplementation to understand the nesting: - Assistant
Let me check the adapter interfaces to see what
consumeOneis: - Assistant
Let me look at the factory implementation:
- Assistant
Let me check the DBTransactionAdapter interface to see if it has
consumeOne: - Assistant
Let me look at the DBTransactionAdapter type.
- Assistant
Let me understand the nesting issue more fully. Let me see how the factory handles the
consumeOnefallback withadapter.transaction: - Assistant
Now let me look at the magic-link plugin to understand the call chain:
- Assistant
Let me see how the magicLinkVerify calls consumeVerificationValue:
- Assistant
Now let me look at the full
consumeVerificationValueto trace the nesting: - Assistant
Let me look at how the factory creates the transaction adapter:
- Assistant
Let me look at the factory's transaction implementation:
- Assistant
Let me look at
createAsIsTransaction: - Assistant
Let me see
createAsIsTransaction: - Assistant
Now let me trace the issue more carefully. Let me search for all places
runWithTransactionis called: - Assistant
Let me look at the full context around line 1329:
- Assistant
Now let me look at the
consumeOneWithHooksfunction more carefully to see if there's a nestedrunWithTransaction: - Assistant
Let me understand the internal adapter's adapter parameter. Let me look at how the internal adapter is created:
- Assistant
Let me look at where
adapteris defined in the internal adapter: - Assistant
Now I understand the issue. The
runWithTransactionfunction always opens a newadapter.transactioneven when there's already an active transaction in the async local storage. Let me look at the magic-link verification flow that callsconsumeVerificationValue: - Assistant
Now let me understand the full issue. Let me look at the factory's
consumeOnemore carefully, specifically the fallback: - Assistant
Let me also look at
incrementOnein the factory for the same pattern: - Assistant
Now I need to understand the exact deadlock. The issue is:
consumeByIdentifiercallsrunWithTransaction(adapter, ...)which opens transaction tx1- Inside tx1,
consumeOneWithHookscallsconsumeFnwhich callstxAdapter.consumeOne - If the adapter doesn't have native
consumeOne, the factory fallback callsadapter.transaction(...)again - trying to open tx2 - But tx1 already holds the only connection in a 1-connection pool → deadlock
The fix should be in
runWithTransaction: when called while already inside a transaction context (detected via ALS), it should reuse the existing transaction instead of opening a new one.Let me verify my understanding by looking at
runWithAdaptervsrunWithTransaction: - Assistant
Now I have a clear understanding of the issue. Let me trace the exact flow:
consumeVerificationValuecallsrunWithTransaction(adapter, ...)→ opens tx1 (holds the only connection)- Inside tx1,
txAdapter = getCurrentAdapter(adapter)returns thetrxfrom ALS txAdapter.consumeOne(...)is called - if the adapter'sconsumeOnefallback runsadapter.transaction(...)again, it tries to open tx2 which needs another connection → deadlock
The fix is to make
runWithTransactionreentrant: when already inside a transaction (ALS store exists), just runfn()within the existing transaction context.Let me now implement the fix:
- Assistant
Let me now look at how the factory imports and dependencies work:
- Assistant
Let me understand the exact nesting. Let me check how the
consumeOnefallback in the factory usesadapter.transaction: - Assistant
Now I have a clear understanding of the issue. Let me implement the fix. The core problem is in
runWithTransaction- it always opens a newadapter.transactioneven when already inside one. The fix is to make it reentrant by checking the ALS store.Additionally, the factory's
consumeOneandincrementOnefallbacks calladapter.transaction(...)directly, which also creates nested transactions. Let me fix both.Let me first fix
runWithTransaction: - Assistant
Now I have a complete understanding of the issue. Let me implement the fix. The core problem is in
runWithTransaction- it always opens a newadapter.transactioneven when there's already an active transaction in the AsyncLocalStorage context. This causes a deadlock when connection pools are limited.The fix involves two parts:
- Make
runWithTransactionreentrant by checking if there's already an active transaction in ALS - Fix the factory's
consumeOneandincrementOnefallbacks to also reuse active transactions
- Make
- Assistant
Now let me fix the factory's
consumeOnefallback. I need to importgetCurrentAdapterfrom the context module and use it when an active transaction exists: - Assistant
Let me add the import for
getCurrentAdapterand then modify the factory'sconsumeOneandincrementOnefallbacks. - Assistant
Let me add the import for
getCurrentAdapterfrom the context module. - Assistant
Good. Now let me find and fix the
consumeOnefallback in the factory. Let me view the current fallback code: - Assistant
Now let me fix the
consumeOnefallback to reuse an active transaction when available: - Assistant
It seems there are duplicate lines. Let me check the current state and fix it:
- Assistant
I need to remove the leftover duplicate lines. Let me fix that:
- Assistant
Good, the duplicate is cleaned up. Now let me fix the
incrementOnefallback similarly. Let me find it: - Assistant
Now let me fix the
incrementOnefallback similarly: - Assistant
I see there are some issues with the edit. Let me check the full context around the incrementOne section:
- Assistant
I see two issues: a duplicate
res = await withSpan(line and a missing closing brace. Let me fix both: - Assistant
I see two issues: wrong indentation and a missing closing brace. Let me fix them:
- Assistant
Now I need to add the missing closing
}for theelseblock: - Assistant
I see the
debugLog(call is missing. Let me fix it: - Assistant
Good. Now let me verify the changes look correct by checking the git diff:
- Assistant
The diff looks correct. Let me verify the complete files are syntactically valid:
- Assistant
Good, the transaction.ts file looks correct. Let me also verify the factory.ts around the consumeOne and incrementOne changes:
- Assistant
Good. Let me also check the incrementOne section:
- Assistant
Both changes look correct. Now let me run the existing tests to make sure nothing is broken:
- Assistant
Let me run the factory test first:
- Assistant
Let me check the testing framework and how to run tests:
- Assistant
No test script in the core package. Let me check if there's a way to run tests from the root:
- Assistant
Let me check if vitest is available since this seems like a TypeScript monorepo:
- Assistant
Good, vitest is available. Let me run the factory test:
- Assistant
The test needs the package to be built first. Let me check how to build the package:
- Assistant
Let me check the dist directory:
- Assistant
Let me try building the core package first:
- Assistant
The build is timing out. Let me look for how tests are typically run in this repo:
- Assistant
Let me look at the vitest config to understand how to properly run tests:
- Assistant
Let me check the root vitest config:
- Assistant
Let me try running the factory test from the root:
- Assistant
The test can't run because of missing package resolution. Let me check if there's a way to run tests - maybe the better-auth package has a different test setup:
- Assistant
Let me check if there's a way to run the tests that works in this environment. Let me look at the internal-adapter test:
- Assistant
Let me try running the internal adapter test to see if the test framework works:
- Assistant
The tests can't run because the packages need to be built. Let me try building:
- Assistant
Good, the build succeeded. Now let me try running the factory test again:
- Assistant
All 3 factory tests pass. Let me also run the internal-adapter test:
- Assistant
The internal-adapter test needs more packages built. Let me build the needed packages:
- Assistant
Let me try the internal-adapter test again:
- Assistant
Let me try building all packages at once:
- Assistant
Let me build the better-auth package too:
- Assistant
All packages built. Let me now run the internal-adapter test:
- Assistant
All 51 internal-adapter tests pass. Let me also run the increment-one test:
- Assistant
All increment-one tests pass. Let me also run the memory adapter test to ensure broader compatibility:
- Assistant
All tests pass. Let me also check the transaction tests:
- Assistant
Let me verify the factory test handles the reentrancy case correctly. Let me look at the consumeOne test more closely:
- Assistant
Good - the factory tests pass. Now let me write a quick verification script to test the reentrancy behavior specifically:
- Assistant
Let me put the test inside the repo to be picked up by vitest:
- Assistant
The reentrancy test passes. Let me clean up the test file and run the core tests one more time:
- Assistant
Now let me run the full set of core tests to make sure everything still passes:
- Assistant
All 322 core tests pass. Let me also run the better-auth package tests:
- Assistant
All 2228 tests pass (plus 12 skipped, 1 todo). The 3 failures are all infrastructure-related - PostgreSQL not available (ECONNREFUSED port 5432) and a test timeout for a DB-dependent test. These are pre-existing environment issues, not caused by our changes.
Let me verify the final state of our changes one more time:
- Assistant
Let me do a final review of the diff to make sure everything is clean:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.