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 thetrxadapter from the ALS store.runWithTransactionis inconsistent with this -- it doesn't reuse.Expected:
runWithTransactionshould be reentrant -- when an adapter/transaction is already active in the async-context store, runfnwithin it instead of opening a nestedadapter.transaction(mirroringgetCurrentAdapter). Then verify needs only one connection and works on any pool size. (Alternatively/additionally, document that adapters MUST support reentrant nested transactions -- currently adapters like@zenstackhq/better-authopen a brand-new transaction on the base client for eachadapter.transactioncall, which is a reasonable contract but incompatible with the current nesting.)This is security-relevant: the 1.6.11 change that introduced this nesting was the magic-link "mint multiple sessions from one token" race fix, so the fix effectively breaks magic-link verification on connection-limited adapters/pools.
What version of Better Auth are you using?
1.6.11
System info
> The `auth info` CLI can't introspect this project headlessly because the auth instance is built dynamically via a factory (no static `auth.ts` export), so the values below are assembled manually { "better-auth": { "version": "1.6.11", "@better-auth/core": "1.6.11" }, "adapter": { "name": "@zenstackhq/better-auth", "version": "3.6.4", "orm": "@zenstackhq/orm 3.6.4 (Kysely 0.28.17)" }, "database": { "driver": "pg 8.20.0", "pool": { "max": 1 }, "fronted_by": "Cloudflare Hyperdrive" }, "runtime": { "platform": "Cloudflare Workers (workerd)", "wrangler": "4.95.0", "node_for_tooling": "v22.22.1" }, "plugins": ["magicLink"], "os": "macOS (Darwin 25.5.0)" }Which area(s) are affected? (Select all that apply)
Backend
Auth config (if applicable)
import { betterAuth } from "better-auth" export const auth = betterAuth({ emailAndPassword: { enabled: true }, });Additional context
- Bisected away unrelated suspects: the hang reproduces on older framework code and is independent of DI scope changes -- it's purely
1.6.10 -> 1.6.11. - Reproduced deterministically in a real
workerdintegration test (request magic link -> capture token -> verify) that times out before the change. - Relevant code:
@better-auth/corecontext/transaction.mjsrunWithTransaction(opensadapter.transactionunconditionally) vsgetCurrentAdapter(reuses the activetrx);internalAdapter.consumeVerificationValue->consumeOneWithHooks-> adapterconsumeOne. - Worked around downstream by making the adapter's transaction reentrant (reuse the in-flight transaction via
AsyncLocalStorage), which is also the correct semantics (nested transaction = one atomic unit) -- but it seems likerunWithTransactionitself should reuse the active transaction.
Interface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /better-auth, current file: none) bash-$
- Assistant
I'll start by exploring the repository structure and locating the
runWithTransactionimplementation mentioned in the issue. - Assistant
Let me look at the transaction.ts file and related code.
- Assistant
I've confirmed
runWithTransactionalways opens a new transaction. Next I'll inspect call sites and existing tests to design a reentrant fix. - Assistant
rg is not found, let me use grep instead.
- Assistant
Hmm empty output. Let me try differently.
- Assistant
Inspecting
consumeVerificationValueand nestedrunWithTransactionusage next. - Assistant
I'll check
consumeOne/ magic-link verify for a nested transaction call. - Assistant
Checking magic-link verify and
consumeOneadapter path for nested transaction calls. - Assistant
Looking at how the adapter factory builds transaction adapters and whether they nest.
- Assistant
Let me look at the full transaction implementation in the factory and how prisma marks transaction adapters as as-is.
- Assistant
Looking at Prisma's approach more carefully - when creating a transaction adapter, it uses
transaction: falsewhich makes the nested adapter's.transactionusecreateAsIsTransaction. Let me see ... - Assistant
I'll check for existing tests around
runWithTransactionand reviewAGENTS.mdguidance. - Assistant
Also note that the guidance says "Bug fixes and new features MUST include tests" and "UNDER NO CIRCUMSTANCES should you modify existing tests or add new tests to the repository" from the system prompt...```typescript export const runWithTransaction = async ( adapter: DBAdapter, fn: () => R, ): Promise => { let called = false; return ensureAsyncStorage() .then(async (als) => { called = true; const existing = als.getStore(); // Reuse any active adapter (transaction or plain) instead of always opening a nested transaction if (existing?.adapter) { return fn(); } const pendingHooks: Array<() => Promise> = []; let result: Awaited; let error: unknown; let has = false; try { result = await adapter.transaction(async (trx) => { return als.
- Assistant
Looking at how internal-adapter gets its
adapterreference - it always uses the base. - Assistant
Checking if magic-link nests transactions via createUser/createSession and looking for git history on this file.
- Assistant
Checking git history and any open PRs or related discussion about this.
- Assistant
I'll make
runWithTransactionreentrant with aninTransactionflag, sincerunWithAdapteralways puts an adapter in ALS. - Assistant
Checking whether
with-hooksor the factory nest anotherrunWithTransaction, and verifying the rest of the file. - Assistant
The factory's
consumeOnefallback may nest real transactions too—I'll check whether we should route it through the active transaction as well. - Assistant
Checking for circular dependency risks if the factory imports from context.
- Assistant
Checking how
consumeVerificationValueevolved — the nesting might haveern been different in 1.6.11. - Assistant
Let me look at how 5f09d566a introduced magic-link atomic consume and the initial consumeVerificationValue.
- Assistant
Let me look at commit a2c0c9346 which added claimOne - maybe the initial version used runWithTransaction differently.
- Assistant
Updating the factory's
consumeOne/incrementOnefallbacks so they reuse an active transaction instead of nesting. - Assistant
I'll add a shared helper that reuses the active transaction and use it from the factory fallbacks.
- Assistant
Exporting the helper and updating the factory next.
- Assistant
I left a broken export — fixing it now.
- Assistant
Now update the factory ves to use withAdapterTransaction.
- Assistant
There's a missing blank line between imports and export - biome might want that. Let me check and also replace the c...
- Assistant
Now replace the consumeOne and incrementOne fallbacks to use withAdapterTransaction.
- Assistant
The replace needs the file to be scrolled to sh ow those lines. Let me use goto.
- Assistant
Now I can replace.
- Assistant
Now update incrementOne similarly.
- Assistant
Replace incrementOne fallback.
- Assistant
I introduced a typo: "theintera One" instead of "the incrementOne". Let me fix that.
- Assistant
Let me look at the exact text.
- Assistant
There's corrupted text "theintera One" became weird unicode. Let me fix with sed.
- Assistant
No python3? Try node.
- Assistant
Fixing a bugodied: if
fnis throws insidewithAdapterTransaction, the catch currentlyopens a new transaction. - Assistant
Also runWithTransaction hasするĂ the same bug - if fn() throws on line 103 when reusing, prefixes catch at 128 with called=true rethrows - goo...
- Assistant
The issue says no new interfaces — I'll stop exporting
withAdapterTransactionfrom the public context index. - Assistant
Writing a temporary scriptoint to verify reentrancy and the deadlock fix.
- Assistant
There's a typo:
Promise<R>>- let me fix and run. - Assistant
Corepack is prompting. Let me try with CI=true or use npx/vite-node from node_modules.
- Assistant
There's vitest but no ts ativx. Let me use vitest or node scripts with experimental strip types, or write a plain JS test.
- Assistant
I'll rebuild the core package and import from dist.
- Assistant
Need to build core package first.
- Assistant
Build completed. Now run the testagainst the densidade دest.
- Assistant
All reentrancy checks passed. Running related existingunit tests next.
- Assistant
Let me also run magic-link tests and consumeVerificationValue tests.
- Assistant
The kysely-adapter needs to be built. Let me try building it or running tests differently.
- Assistant
Retrying the tests now that dependencies a re built.
- Assistant
Many packages need building. Checking how the test setup resolves packages.
- Assistant
Building the remaining packages the tests depend on.
- Assistant
Now rerun the tests.
- Assistant
consumeVerificationValue tests passed.Running full magic-link and prisma adapter reentrancy tests next.
- Assistant
The -t filter appliedSample to all. Let me run magic-link fully.
- Assistant
All magic-link tests pass. Reviewing the finaldiff and cleaning up.
- Assistant
Restoring the trailing newline in
index.ts. - Assistant
Checking the public API rang and final git status.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →