Skip to content
TheChatArchiveThe Chat Archive
gpt-5.6-sol· openaiHugging 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. Assistant

    I’ll locate the transaction context implementation and its tests, then reproduce the nested transaction behavior with the smallest relevant test before patching reentrancy.

  3. Assistant

    ripgrep is unavailable, so I’ll use grep to identify the source and test coverage.

  4. Assistant

    I found the core implementation. I’ll inspect its store shape, transaction semantics, and package test conventions to ensure reentrancy does not accidentally reuse a transaction belonging to a different base adapter.

  5. Assistant

    The store currently represents both runWithAdapter and transaction scopes without an explicit transaction flag. Since getCurrentAdapter deliberately reuses any active adapter, the requested consistency suggests nested runWithTransaction should execute directly whenever a store exists, preserving the outer pending-hook queue. I’ll inspect adapter typing and call patterns, then use a temporary Vitest file (removed afterward) to demonstrate the current double transaction call.

  6. Assistant

    A nested call currently invokes adapter.transaction twice, which is the deadlock trigger even without a real database. I’ll reproduce that with a temporary script outside the repository; the fake transaction adapter only needs the transaction method because the callback does no CRUD.

  7. Assistant

    The reproduction script was created, but Corepack tried to prompt for a newer pnpm version, which this noninteractive environment cannot answer. I’ll invoke the already-installed local tsx/Vitest tooling directly if present.

  8. Assistant

    There is no local tsx, so I’ll temporarily place the reproduction under the core package for Vitest module resolution, run it, and immediately remove it. This is only a local diagnostic and will not be part of the change.

  9. Assistant

    The package-local config lacks the workspace aliases required by this self-import. I’ll rerun the same temporary diagnostic with the repository Vitest config, which defines those aliases.

  10. Assistant

    The diagnostic runner is blocked by an existing workspace self-resolution problem, but source inspection exposes an important edge case: every auth request is already wrapped by runWithAdapter, so merely checking getStore() would suppress all real transactions. I’ll inspect history and the wrapper to choose a robust transaction marker rather than relying on adapter object identity (transaction adapters may be the same object).

  11. Assistant

    I’ll add an internal isTransaction marker to distinguish the request-level adapter context from an actual transaction. Nested transaction calls will return fn() directly, retaining the active transaction adapter and outer pending-hook queue; top-level calls inside runWithAdapter will still open exactly one transaction. I’ll keep the marker internal, so no public adapter interface changes.

  12. Assistant

    Python is not installed, so no edit occurred. I’ll apply the same focused changes with the repository’s edit/replace tools.

  13. Assistant

    The reentrancy guard is now in place. I’ll format/check the file, inspect workspace package links, and then rerun the temporary regression with a resolver workaround if necessary.

  14. Assistant

    Biome formatted the change cleanly. To bypass the unrelated missing self-link, I’ll temporarily rewrite only the self-import to its equivalent relative source path, run diagnostics covering (1) direct nesting, (2) nesting under the normal request wrapper, (3) active transaction adapter reuse, and (4) after-transaction hook timing, then restore the import and remove the diagnostic file.

  15. Assistant

    The regression diagnostic now passes: one transaction is opened under the request wrapper, both nested scopes see the same transaction adapter, and the queued hook runs only after commit. I’ll run the core TypeScript check and existing core test project next.

  16. Assistant

    Type checking passes. The full core suite has 306 passing tests, with three suites unable to load because pre-existing workspace self-links for @better-auth/core/async_hooks and /instrumentation are absent—the same environment issue encountered before the patch. I’ll make the internal marker optional to preserve compatibility for advanced callers of the exposed AsyncLocalStorage, then perform final formatting and diff review.

  17. Assistant

    The editor helper did not apply the one-character optionality change despite finding it, so I’ll use a noninteractive sed replacement and recheck.

  18. Assistant

    To complete the reported-error checklist explicitly, I’ll now run the diagnostic against a temporary simulation of the pre-fix implementation (guard removed). It should observe two transaction acquisitions—the precise pool-size-one deadlock trigger—then restore the fixed source byte-for-byte.

  19. Assistant

    The pre-fix simulation confirms two transaction acquisitions, while the fixed diagnostic confirmed one acquisition with correct transaction adapter and hook behavior. I’ll do one final source/diff sanity check, ensure no temporary files remain, and then submit.

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