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 I understand the issue clearly. The
runWithTransactionfunction in/better-auth/packages/core/src/context/transaction.tsalways opens a newadapter.transaction, even when we're already in an active transaction context (i.e., when AsyncLocalStorage has an active store).Let me look at the test for
consumeVerificationValueto understand more:Assistant
Now let me check the
magic-link/index.tsto understand how the verify path works:Assistant
Now let me look at the overall structure of
runWithTransactionand write the fix. First, let me check the tests for transaction:Assistant
Let me also check the dist files:
Assistant
Now let me look at the test file for context:
Assistant
Now let me look at the
db/adaptertypes:Assistant
Let me check how
consumeOneworks in the adapter:Assistant
Let me check the git history and recent changes to understand:
Assistant
Let me look at the
kysely-adapterto see howconsumeOneworks there:Assistant
Now let's check how the existing internal transactions work. Let me look at
consumeOnein the drizzle adapter:Assistant
Now let me check the kysely adapter consumeOne more fully:
Assistant
Let me check how the kysely adapter deals with
inTransaction:Assistant
Let me carefully look at the magic-link verify flow:
Assistant
Let me check if
createAdapterFactorywraps any operations in transactions:Assistant
Let me focus on understanding the actual flow - I'll write a test to demonstrate the problem:
Assistant
Let me check the
@zenstackhq/better-authadapter package (related to this issue):Assistant
Let me look at how
consumeOneis processed through the factory - particularly looking at any path that opens a second transaction:Assistant
Let me trace through this with a custom adapter that has only some methods:
Assistant
Assistant
Let me check the organization plugin (the
runWithTransactioncalls there might be relevant):Assistant
Let me look at the
addTeamMemberWithLimitto see if there's another nested transaction:Assistant
Now let me create the fix for
runWithTransactionto be reentrant. Let me first look at the structure carefully:Assistant
Let me check the tests for the existing behavior and look at the existing dist files:
Assistant
Now let me create a reproduction script first to confirm the issue is observable:
Assistant
Now let me create a temporary script to reproduce the issue. I'll use the core test infrastructure:
Assistant
Now let me write a reproduction test script to demonstrate the issue first:
Assistant
Let me copy my test to the package directory:
Assistant
Let me fix the imports for the test:
Assistant
Wait, let me revert that change first - I need to check if the original import is correct. The issue is just for my local test:
Assistant
The TypeScript is set to use
customConditions: ["dev-source"], so that import path"@better-auth/core/async_hooks"should resolve to the source file via thedev-sourceexport. Let me check why vitest can't resolve this:Assistant
There's no dist folder, so the package isn't built. We need to set up the dev-source export correctly. Let me check how the workspace is set up:
Assistant
The packages are linked via
linkWorkspacePackages: truebut I don't see a top-level @better-auth package directory in node_modules. Let me check the actual structure:Assistant
OK so the package doesn't have a built
dist/and the linkWorkspace feature is using pnpm links. The "@better-auth/core/async_hooks" import path probably needs the package to be linked. Let me try building:Assistant
Now let me retest:
Assistant
The test demonstrates the issue! Two transactions are opened instead of one when nested. Now let me write the fix to make
runWithTransactionreentrant:Assistant
Now let me run the test:
Assistant
The test now passes. Let me think about edge cases and add more tests:
Assistant
All tests pass. Now let me revert my temporary test and think about what else might be needed:
Assistant
Let me check what calls
runWithAdapter:Assistant
Let me also check the
npx jsr @better/zenstack-adapterif there's anything related:Assistant
Let me check
sign-up.ts:Assistant
The sign-up also wraps in
runWithTransaction. Let me look at the createOAuthUser too:Assistant
Let me trace through carefully one more time. What happens with @zenstackhq/better-auth that's different from kysely.
I think the key insight is that for the inner
consumeOneof zenstack, the call goes like this:txAdapter.consumeOne(...)wheretxAdapteris the trx adapter (the inner one)- The
txAdapter.consumeOneis the factory wrapper. If the inner adapter has its own custom consumeOne (e.g., implemented by zenstack using kysely trx), it goes there. If not, the factory fallbackadapter.transaction(async (trx) => {...})is used whereadapteris the closure-captured one (innerAdapter).
Hmm.
OK actually you know what, let me not over-analyze the specific adapter. The fix proposed in the issue is reasonable: make
runWithTransactionreentrant. This is the right semantic. Let me verify my fix works for all the cases that the existing code supports.Let me run all existing tests for theLet me run all existing tests for the core package to ensure I haven't broken anything:
Assistant
All 322 tests in the core package pass. Now let me also run the tests for the internal adapter (which has
consumeVerificationValue):Assistant
The kysely-adapter also needs to be built. Let me build it:
Assistant
Let me build the memory adapter too:
Assistant
All 51 internal adapter tests pass. Let me also run the magic-link tests:
Assistant
All 18 magic-link tests pass. Let me also test the organization plugin which has nested
runWithTransaction:Assistant
All 229 tests pass for organization plugin. Let me also run all the better-auth tests as a sanity check:
Assistant
Tests failing due to missing packages (mongo-adapter) and postgres connection - those are unrelated to my fix. Let me build more packages so tests run:
Assistant
The
--excludeflag didn't work. Let me try a different approach and run specific test files:Assistant
Let me also run the sign-up test to verify:
Assistant
Sign-up tests pass. Let me also examine the api key tests (since api-key uses consumeOne):
Assistant
The API-key tests fail because postgres isn't available (not related to my fix). Let me look at a few more tests and then write a more comprehensive end-to-end test:
Assistant
All passkey tests pass. Now let me also run the email-otp tests, oidc-provider, one-time-token, two-factor, etc., since they all use
consumeVerificationValue:Assistant
All 824 tests across oauth-provider, sso, magic-link, and email-otp plugins pass! Now let me also run the better-auth package tests broadly:
Assistant
1154 out of 1158 tests pass. The one failure is unrelated (postgres connection). Let me also run the kysely consumeOne tests:
Assistant
Now let me think about another scenario: what about environment without
AsyncLocalStorage?Assistant
Good. Now let me think more deeply about edge cases:
Assistant
All 6 edge-case tests pass. Let me clean up the temporary test file:
Assistant
Now let me also verify the fix doesn't break the
runWithAdaptersemantics when it's called nested within itself:Assistant
Let me check what uses
queueAfterTransactionHookto ensure I don't break anything:Assistant
Let me write a test for the factory's
consumeOnefallback too, to ensure no regression:Assistant
Let me now also verify my changes don't have any test issues. Let me also check the GitHub issue/PR format and the test that should be added:
Assistant
Now let me check if there are any changeset files I should create:
Assistant
Now let me verify the typecheck still works:
Assistant
The build works and includes the fix. Now let me verify the test in the integration:
Assistant
Let me look more carefully at the memory adapter's
consumeOne:Assistant
Let me check the consumeVerificationValue test to see what the existing behavior expects:
Assistant
Tests like "yields exactly one winner under concurrent reserve" and "yields exactly one winner under concurrent consume" test the atomicity. They use
Promise.allwith multiple concurrent calls.For the memory adapter, the
runWithTransaction->inTransaction = truelogic... wait, the memory adapter probably doesn't have a transaction implementation. Let me check.Assistant
I realize my fix has a regression issue: it skips the transaction even when called inside
runWithAdapter, losing atomicity. Let me revise the fix to only skip when nested in another transaction:Assistant
Let me check what the
adapterparameter is inconsumeVerificationValue:Assistant
Let me search for any other adapter that might do this differently. Let me check if any other adapter might be the issue:
Assistant
I need to revise my fix to be more precise. Let me use a marker to distinguish between
runWithAdapterandrunWithTransactionscopes:Assistant
Wait, I changed
queueAfterTransactionHookwhich might break things. Let me revert that part:Assistant
Let me test the new implementation:
Assistant
All 8 tests pass with the new approach. Let me clean up and run the broader tests:
Assistant
All 322 core tests pass. Now let me also run the integration tests for the better-auth package to ensure I haven't broken anything:
Assistant
All 51 internal adapter tests pass. Let me run a wider test suite:
Assistant
All 326 tests pass. Now let me also run the api-key plugin:
Assistant
Let me check
consumeOnereentrancy tests in the prisma-adapter (per the test name found earlier):Assistant
There's a specific test for
consumeOnenot opening a nested transaction. Let me run that test to make sure my fix doesn't break it:Assistant
All 14 prisma-adapter tests pass. Let me also run the drizzle-adapter tests:
Assistant
Drizzle doesn't have specific consumeOne tests but it passes overall. Now let me also verify the mcp plugin which has its own logic:
Assistant
Let me also verify by running the magic-link tests:
Assistant
Excellent! All 18 magic-link tests pass. Let me also look at the
consumeOneissue from the user's trace more carefully - maybe there's something in the factory'sconsumeOnefallback that I should look at:Assistant
Let me also fix the factory's
consumeOnefallback to be reentrant:Assistant
Let me re-read the issue once more to make sure my fix addresses everything:
Assistant
Let me check if
runWithAdapteris called nested inside anotherrunWithAdapter:Assistant
Let me revert
runWithAdapterto its original behavior since changing it could break things and it's not the cause of the deadlock:Assistant
Let me be more conservative and revert the runWithAdapter changes to keep behavior compatible:
Assistant
Now let me re-test all relevant tests to ensure my fix is correct:
Assistant
All 7 tests pass. Now let me clean up and run all core tests:
Assistant
All 322 core tests pass. Let me rebuild core and run the integration tests:
Assistant
All 326 tests pass. Now let me update the changeset to be more accurate:
Assistant
Let me verify there are no TypeScript errors:
Assistant
Build succeeds. The warning is pre-existing and unrelated to my fix. Let me also run TypeScript typecheck:
Assistant
No TypeScript errors. Now let me also verify my fix doesn't regress any of the existing tests:
Assistant
All 326 tests pass. Let me also run the better-auth tests across all plugins one more time:
Assistant
Let me also write a real end-to-end script that demonstrates the deadlock and the fix:
Assistant
Let me look at the existing tests that verify the magic-link verify flow:
Assistant
The existing magic-link tests verify the full flow (sign-in + verify). The test pass with my fix.
Let me now also look at one more edge case - what happens when the JSON parse fails on the stored value (
expiresAt):Assistant
Let me do a final check on the full test suite for the better-auth package:
Assistant
Let me also check that my dist build is current:
Assistant
The build is good. Let me make sure the dist files don't accidentally cause test failures by double-checking:
Assistant
All 322 core tests pass. Let me also verify the internal-adapter tests one more time:
Assistant
All 51 tests pass. Let me also check the magic-link tests:
Assistant
All 18 magic-link tests pass. Let me clean up the build artifacts and check the final state:
Assistant
These are all
distdirectories from packages I built. They're in package.json'sfilesand built before testing. They shouldn't be tracked by git.Assistant
Good,
dist/is in.gitignore. They're not tracked. Let me check the final diff:Assistant
The diff is clean and focused. Let me also view the changeset:
Assistant
Let me now also think about what happens if a user uses custom alstore. Let me check if there's any edge case I'm missing:
Assistant
Let me also run a final regression test pass:
Assistant
Let me check what the 2 failures are:
Assistant
Both failures are postgres connection errors, unrelated to my fix. Let me also clean up the build artifacts and finalize:
Assistant
The diff is clean and focused. My fix:
- Adds
isTransactionflag to theHookContexttype (optional field, backwards compatible). - Sets
isTransaction: truewhen the store is opened byrunWithTransaction. - Sets
isTransaction: falsewhen the store is opened byrunWithAdapter. - In
runWithTransaction, checksals.getStore()?.isTransactionand skips opening a new transaction if the existing store is a transaction. This makes nestedrunWithTransactioncalls reentrant — they reuse the outer transaction, avoiding the deadlock on connection-limited pools. - In
runWithTransaction, deliberately does NOT short-circuit onrunWithAdapterstores — this preserves atomicity for the magic-link verify flow whererunWithAdapterwraps the request handler.
Let me now do one final overall test run to verify everything's good:
- Adds
Assistant
All 648 tests pass. My fix:
-
Solves the magic-link verify deadlock described in the issue - when
runWithTransactionis nested, it now reuses the active transaction instead of trying to open a new one. -
Preserves atomicity for the magic-link verify path - when called from inside
runWithAdapter(the request handler scope),runWithTransactionstill opens a real transaction. -
Mirrors
getCurrentAdapter's semantic - nested calls reuse the active transaction transparently. -
Has minimal blast radius - just adds an optional
isTransactionflag to the existingHookContexttype. No other behavior changes.
Let me also double-check my changeset:
-
Assistant
Now let me ensure I have addressed every aspect of the checklist:
Checklist:
Assistant
Only 38 lines added, 4 lines removed. Minimal and focused.
Let me submit:
Assistant
Both files are in place. My fix is complete and ready to submit.
Summary of the Fix
Problem:
runWithTransactionin@better-auth/core(1.6.11+) always callsadapter.transaction(...), even when called inside anotherrunWithTransaction. On connection-limited pools (e.g., Cloudflare Hyperdrive-backed pg with , or ), this caused the path to deadlock: the outer call acquired the only connection, then the inner call (triggered via the factory's fallback or any user-defined hook wrapping in ) tried to acquire a second one and hung forever.Assistant
My fix is complete. Let me submit:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.