Skip to content
TheChatArchiveThe Chat Archive
composer-2.5· unknownHugging Face ibragim-bad/swe_rebench_07_2026_trajectories

magic-link verify deadlocks: runWithTransaction nests adapter.transaction (1.6.11…

  1. User

    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

    1. better-auth 1.6.11 with the magicLink plugin.
    2. 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).
    3. 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.
    4. await auth.api.signInMagicLink({ body: { email } }) -> works (single insert).
    5. 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. runWithTransaction is inconsistent with this -- it doesn't reuse.

    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)

    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 workerd integration test (request magic link -> capture token -> verify) that times out before the change.
    • Relevant code: @better-auth/core context/transaction.mjs runWithTransaction (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.

    Interface

    No new interfaces are introduced.

  2. Assistant

    Investigating transaction nesting in runWithTransaction and how getCurrentAdapter reuses the active transaction.

  3. Assistant

    Implementing reentrant runWithTransaction and adding tests. Checking factory imports for the consumeOne fallback fix.

  4. Assistant

    Fixing async usage in the factory: moving awaits outside the withSpan callback.

  5. Assistant

    Fixing TypeScript errors in tests and factory.

  6. Assistant

    Yes — this is a valid GitHub issue, and the root cause is real. I've implemented the fix in this repo.

    Root cause

    runWithTransaction always called adapter.transaction(), even when a transaction was already active in async context storage. That diverged from getCurrentAdapter, which correctly reuses the active transaction adapter.

    With consumeVerificationValue (1.6.11) wrapping work in runWithTransaction, any nested transaction attempt on a single-connection pool (e.g. Hyperdrive with max: 1) deadlocks: the outer transaction holds the only connection while the inner one waits forever.

    Fix

    1. Reentrant runWithTransaction (packages/core/src/context/transaction.ts)

    • Added an inTransaction flag to the async-context store
    • Nested runWithTransaction calls reuse the active transaction instead of opening a new one
    • runWithAdapter (per-request context, not a DB transaction) does not set inTransaction, so runWithTransaction still opens a real transaction as expected
    • Exported isInTransaction() helper
    • Fixed a pre-existing bug: let called = true → let called = false in the error fallback path

    2. Adapter factory fallbacks (packages/core/src/db/adapter/factory.ts)

    • consumeOne and incrementOne fallbacks (for adapters without native implementations) now run inline when already inside a transaction, instead of calling adapter.transaction() again

    Tests added

    • packages/core/src/context/transaction.test.ts — nested runWithTransaction opens only one transaction; runWithAdapter + runWithTransaction still works; after-transaction hooks fire once
    • packages/core/src/db/adapter/factory.test.ts — consumeOne fallback doesn't nest when already in a transaction

    All 8 new/updated tests pass; @better-auth/core typecheck passes.

    This should unblock magic-link verify on connection-limited pools without requiring downstream adapters (like @zenstackhq/better-auth) to implement reentrant transactions themselves.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.