Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-sonnet-5· anthropicHugging Face ibragim-bad/swe_rebench_07_2026_trajectories

ISSUE DESCRIPTION magic-link verify deadlocks: runWithTransaction nests…

  1. 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

    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.

    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 using git reset --hard command. Additionally, you can use git stash and git stash pop to temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you call submit) using git status or git diff commands. However you don't need to use git add or git commit before submitting your changes. In fact, submit only submits currently unstaged changes because it uses git diff to 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-$

  2. Claude Assistant

    Now let's check where consumeVerificationValue / consumeOneWithHooks are, to understand nesting and ensure this fix actually resolves it.

  3. Claude Assistant

    Need to run vitest from root, not from packages/core directly.

  4. Claude Assistant

    Good, better-auth package properly links to core. Let's move the test there instead to verify via existing internal-adapter tests, and also write a targeted reentrancy test importing from better-auth's node_modules resolution.

  5. Claude Assistant

    Now dist exists. Let's rerun the test.

  6. Claude Assistant

    Both pass. Let's also verify the "before fix" behavior actually deadlocked/double-called transaction, to confirm the test is meaningful.

  7. Claude Assistant

    This confirms the fix is meaningful (transaction was nested/called twice before fix). Now restore the fix.

  8. Claude Assistant

    Now let's run the existing relevant test suites to make sure nothing is broken: internal-adapter tests, magic-link tests, organization tests, sign-up tests, and core context tests.

  9. Claude Assistant

    All 51 tests pass. Now let's test magic-link, sign-up, and organization test suites.

  10. Claude Assistant

    All pass. Now let's run the broader core package test suite and better-auth full test suite to be thorough (might take a while, but let's try).

  11. Claude Assistant

    All core tests pass now that dist exists. Let's run the full better-auth package test suite.

  12. Claude Assistant

    Confirmed pre-existing, environment-related (no Postgres available), unrelated to my fix. Restore the fix.

  13. Claude Assistant

    Now let's clean up: remove temp test file and remove generated dist directories (since they weren't there originally and shouldn't be part of the submission diff, though dist is likely gitignored anyway).

  14. Claude Assistant

    Good, dist is gitignored so those build artifacts won't be included in the diff. Let's verify the final diff.

  15. Claude Assistant

    Type-checking passes cleanly. Let's do a final review of the changed file to make sure everything looks correct.

  16. Claude Assistant

    This looks good. Let's clean up the temporary symlink I created for testing purposes (though it's in node_modules so not tracked anyway, but let's verify).

  17. Claude Assistant

    Both are gitignored, confirming the final diff only contains the intended source change.

  18. Claude Assistant

    Checklist Review

    • If an error was reported in the issue description, I have successfully reproduced it. I traced the exact code path described in the issue (runWithTransaction in packages/core/src/context/transaction.ts) and confirmed via a targeted reentrancy test (using a fake adapter that counts transaction() invocations) that, prior to the fix, a nested runWithTransaction call opens a second adapter.transaction() even though one is already active in the async-context store — exactly the nesting described in the issue that causes the deadlock on connection-limited pools. I verified this by reverting my fix and re-running the test: transactionCalls was 2 instead of 1, proving the nested-transaction bug is real and my test captures it.

    • If an error was reported in the issue description, I have confirmed that my fix resolves the error. After applying the fix, the same test shows transactionCalls === 1 — the nested call reuses the already-active transaction adapter via fn() directly instead of calling adapter.transaction() again, mirroring the existing reentrant behavior of getCurrentAdapter. This removes the second, blocking adapter.transaction() call that was causing the deadlock.

    • I have thought about edge cases and made sure my fix handles them as well.

      • Non-nested calls (no active transaction in the store) still go through the original adapter.transaction() path unchanged, verified by a second test case.
      • pendingHooks semantics are preserved: since the nested call reuses the same store object (not a new one), any queueAfterTransactionHook calls made inside the nested fn() still get pushed onto the outer transaction's pendingHooks array and execute only after the outermost transaction completes/commits — they are not run prematurely at the end of the inner logical call.
      • The change only affects runWithTransaction; runWithAdapter and getCurrentAdapter (already reentrant) are untouched.
      • Confirmed via existing test suites (consumeVerificationValue, magic-link, organization CRUD routes, sign-up) that nothing regressed, since these already relied on the pre-existing (non-nested) behavior.
    • I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. Ran:

      • packages/core full test suite (322 tests) — all passing.
      • packages/better-auth/src/db/internal-adapter.test.ts (51 tests, including all consumeVerificationValue cases) — all passing.
      • packages/better-auth/src/plugins/magic-link (18 tests) — all passing.
      • packages/better-auth/src/api/routes/sign-up.test.ts and packages/better-auth/src/plugins/organization/** (which use runWithTransaction directly) — all passing.
      • Full packages/better-auth suite (2246 tests) — only 3 failures, all due to ECONNREFUSED 127.0.0.1:5432 (no local Postgres server available in this sandbox) and a related timeout — confirmed via git stash that these same failures exist identically without my change, so they are pre-existing environment limitations, not regressions from this fix.

    The fix is minimal (13 lines added, no lines removed) and precisely targets the reentrancy gap identified in the issue.

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