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 magicLink plugin.
A database adapter whose transaction is a real interactive DB transaction that holds a dedicated connection for its duration (e.g. the Kysely adapter, or @zenstackhq/better-auth, backed by pg).
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.magicLinkVerify({ query: { token } }) (or GET /api/auth/magic-link/verify?token=...).
Minimal trigger: any setup where adapter.transaction acquires 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 verification SELECT; 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 inside runWithTransaction -> opens transaction tx1 (BEGIN, takes the only pooled connection).
Consuming the row (consumeOne) triggers another runWithTransaction -> calls adapter.transaction again -> transaction tx2, which tries to acquire a second connection.
runWithTransaction in @better-auth/core (context/transaction.mjs) always opens a fresh adapter.transaction; it does NOT check adapterAsyncStorage.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 trx adapter from the ALS store. is inconsistent with this -- it doesn't reuse.
Assistant
Now I'll implement the fix in runWithTransaction:
Assistant
I also fixed the let called = true typo (the no-ALS fallback was dead code — compare runWithAdapter at line 47). Let me check the existing test file for conventions:
Assistant
No gh CLI available to find the issue number, so I'll reference the report descriptively. Now the test file:
Assistant
Pre-existing tests fail the same way — the workspace isn't fully installed. Let me check:
Assistant
Tests depend on the package being built (self-referenced subpath exports resolve to dist/). Let me build core:
Assistant
All 5 pass. Now verify the regression test actually fails without the fix:
Assistant
3 of 5 fail without the fix, all pass with it. Now run typecheck and lint:
Assistant
Both failures are ECONNREFUSED 127.0.0.1:5432 — they need a Postgres Docker container, which isn't running in this environment. Let me confirm they're unrelated to my change:
Assistant
Repo-wide typecheck passes. Final diff:
Assistant
Done. The fix is implemented and verified.
Summary
(): unconditionally opened a fresh , so nested calls opened a second interactive DB transaction while the outer one still held its connection — deadlocking any pool that can't hand out two connections (e.g. with behind Cloudflare Hyperdrive). This was inconsistent with , which already reuses the active from the ALS store.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Expected:runWithTransaction should be reentrant -- when an adapter/transaction is already active in the async-context store, run fn within it instead of opening a nested adapter.transaction (mirroring getCurrentAdapter). 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-auth open a brand-new transaction on the base client for each adapter.transaction call, 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)
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 workerd integration test (request magic link -> capture token -> verify) that times out before the change.
Relevant code: @better-auth/corecontext/transaction.mjsrunWithTransaction (opens adapter.transaction unconditionally) vs getCurrentAdapter (reuses the active trx); internalAdapter.consumeVerificationValue -> consumeOneWithHooks -> adapter consumeOne.
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 like runWithTransaction itself should reuse the active transaction.
runWithTransaction is now reentrant: when the async-context store holds an active transaction, fn runs within it instead of opening a nested adapter.transaction. After-commit hooks queued by the nested call land on the outer store's pendingHooks, so they still execute after the outermost transaction settles — correct "one atomic unit" semantics.
Detection uses a new internal inTransaction flag on the ALS store rather than mere store presence, because runWithAdapter (which wraps every request handler via auth/base.ts:89) also populates the store — with the base adapter, which must still trigger a real transaction.
Also fixed a latent typo: let called = true → false, making the documented no-ALS fallback (run fn without a transaction, mirroring runWithAdapter) reachable instead of dead code.
Verified live nesting in HEAD: crud-invites.ts:755 (accept-invitation) → addTeamMemberWithLimit (organization/adapter.ts:943) nests runWithTransaction exactly like the reported magic-link path — now joins the outer transaction (1 adapter.transaction call instead of 2).
Tests (packages/core/src/context/transaction.test.ts, 5 tests): a fake adapter simulating a single-connection pool that fails fast if a second transaction is requested while one is active. Confirmed 3/5 fail on unfixed code, all pass with the fix. Covers: reuse of active trx (regression), runWithAdapter store not mistaken for a transaction, sequential calls still get separate transactions, nested hooks run after outer commit, error propagation from a reentrant call.
Checks: new tests pass; core context + adapter factory suites (15), magic-link (18), organization (229), sign-up/db suites pass; repo-wide pnpm typecheck and Biome pass. The only 2 failures (db.test.ts) require Postgres/MongoDB Docker containers that aren't running here and are unrelated to this change.
Note: I couldn't add the @see issue URL to the regression test (no gh/network to look up the issue number) — the test carries a descriptive comment of the report instead; worth adding the URL before the PR.