Skip to content
TheChatArchiveThe Chat Archive
GLMz-ai/glm-5.2· unknownHugging 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. GLM Assistant

    I'll start by exploring the repository structure and finding the relevant files mentioned in the issue.

  3. GLM Assistant

    Now let me look at how runWithTransaction is used and find consumeVerificationValue:

  4. GLM Assistant

    Let me look at the consumeVerificationValue implementation in the internal-adapter:

  5. GLM Assistant

    Now let me look at consumeOneWithHooks to understand the nesting:

  6. GLM Assistant

    Now let me look at the consumeOneWithHooks in with-hooks:

  7. GLM Assistant

    Let me look at the magic-link verify path:

  8. GLM Assistant

    Let me look at the code around line 124 to understand another runWithTransaction usage:

  9. GLM Assistant

    Let me check the adapter's consumeOne implementation to understand where the second transaction comes from:

  10. GLM Assistant

    Now I see. Let me look at the consumeOne implementation in the factory, especially the fallback path that calls adapter.transaction.

  11. GLM Assistant

    Let me look at the factory's transaction implementation to understand how the transaction adapter (trx) is built and whether consumeOne is on it:

  12. GLM Assistant

    Let me look at createAsIsTransaction and how the transaction adapter is constructed:

  13. GLM Assistant

    Let me check the kysely adapter's consumeOne and transaction:

  14. GLM Assistant

    Let me look at the kysely transaction implementation to understand what methods the trx adapter exposes:

  15. GLM Assistant

    Let me look at the transaction test suite to understand the expected contract:

  16. GLM Assistant

    Let me look at the consumeVerificationValue test to understand the expectations:

  17. GLM Assistant

    Let me check for existing tests related to runWithTransaction in the core package:

  18. GLM Assistant

    Now let me write a reproduction script to confirm the deadlock. First, let me check the build/test setup:

  19. GLM Assistant

    Now let me create a reproduction script that demonstrates the deadlock with a single-connection-pool adapter:

  20. GLM Assistant

    Let me fix the imports to be relative within the core package:

  21. GLM Assistant

    The factory.test.ts is in packages/core/src/db/adapter/ and it imports from ./factory. Let me check how factory.test.ts resolves @better-auth/core/instrumentation. Let me look at the package.json exports and the instrumentation path.

    Actually, the issue is that the factory.ts imports from @better-auth/core/instrumentation (a self-package import). This requires the package to be resolvable. Let me check if there's an alias or if the package resolves to itself.

    Let me check the existing factory.test.ts - it imports ./factory directly. The instrumentation import inside factory.ts is @better-auth/core/instrumentation. Let me check how this resolves.

    Let me check the tsconfig and the dev-source condition. The vitest config uses conditions: ["dev-source"]. Let me check the package.json exports for ./instrumentation.

  22. GLM Assistant

    The @better-auth/core/instrumentation export exists. The issue is the self-referencing package import. In Node.js, a package can reference itself by name only if it's properly set up. Let me check the factory.test.ts to see how it's run. Let me check if there's a node exports self-reference resolution issue. Let me run the factory.test.ts to confirm it works.

  23. GLM Assistant

    Even the existing factory.test.ts fails. Let me check the node_modules linking for @better-auth/core:

  24. GLM Assistant

    So the @better-auth/core package isn't linked to itself in node_modules. The self-reference @better-auth/core/instrumentation cannot be resolved. This means the tests for the core package can't resolve self-references.

    Let me check the pnpm-workspace.yaml and how the workspace packages are linked. Maybe I need to build the core package first, or there's a different resolution.

    Actually wait - the factory.test.ts is an existing test that presumably passes in CI. So there must be a way to resolve @better-auth/core/instrumentation. Let me check the vitest config more thoroughly - maybe there's an alias in the core package's own vitest config.

  25. GLM Assistant

    The runWithTransaction itself is in transaction.ts. Let me check its imports to avoid the instrumentation issue:

  26. GLM Assistant

    Let me check how the existing context test (request-state.test.ts) resolves @better-auth/core/async_hooks:

  27. GLM Assistant

    Even the existing request-state.test.ts fails with the same self-reference resolution issue. The workspace packages aren't linked. Let me check the install state and try to fix it:

  28. GLM Assistant

    The workspace packages aren't linked. Let me run pnpm install to set up the workspace links:

  29. GLM Assistant

    @better-auth/core is linked in the pnpm virtual store but the self-reference from within the package isn't resolving through vitest. Let me check the vitest resolution and try creating the root-level symlink that pnpm normally creates:

  30. GLM Assistant

    Let me remove the factory dependency and test only transaction.ts with a minimal mock adapter:

  31. GLM Assistant

    The self-reference @better-auth/core/async_hooks isn't resolving even with the root symlink. Let me verify the export path and check the resolution:

  32. GLM Assistant

    Let me create a self-link within the core package's node_modules so the self-reference resolves locally:

  33. GLM Assistant

    The dev-source condition resolution isn't working through vitest. Let me try building the core package so the dist exists:

  34. GLM Assistant

    The build succeeded. Now let me re-run the test:

  35. GLM Assistant

    I've reproduced the deadlock. The nested runWithTransaction opens tx2 which tries to acquire a second connection held by tx1 → deadlock. Now let me implement the fix in runWithTransaction:

  36. GLM Assistant

    Now let me apply the fix to make runWithTransaction reentrant:

  37. GLM Assistant

    Let me use the edit command directly. First, let me open the file:

  38. GLM Assistant

    Now let me run the reproduction test to verify the deadlock is fixed:

  39. GLM Assistant

    The deadlock is fixed for the nested runWithTransaction case. Now let me investigate the consumeOne factory fallback, since the issue trace mentions consumeOne triggering the second transaction. Let me check the git history of the 1.6.11 change:

  40. GLM Assistant

    Let me look at how the magic-link verify was changed to use consumeVerificationValue:

  41. GLM Assistant

    Let me check whether the factory tests can run now that dist is built, and test the consumeOne fallback with a single-connection pool:

  42. GLM Assistant

    Now let me write a more comprehensive repro that tests the consumeOne factory fallback (for adapters without native consumeOne) with a single-connection pool, to determine if it also deadlocks:

  43. GLM Assistant

    The consumeOne fallback is safe for standard adapters (trx built with transaction: false). Let me check if @zenstackhq/better-auth is available anywhere to understand its actual structure:

  44. GLM Assistant

    Let me test the scenario where the trx's transaction is also real (non-standard adapter) to see if the consumeOne fallback deadlocks:

  45. GLM Assistant

    This confirms that for non-standard adapters (like @zenstackhq which "opens a brand-new transaction on the base client for each adapter.transaction call"), the consumeOne factory fallback ALSO deadlocks, and the runWithTransaction fix alone doesn't help. Let me check the factory imports and the fallback code to also make it reentrant:

  46. GLM Assistant

    The factory doesn't import the ALS store. Let me check the db/adapter/index.ts to understand potential circular dependency:

  47. GLM Assistant

    Let me check what db/adapter/index.ts re-exports (does it re-export the factory?).

  48. GLM Assistant

    Let me check the factory's deleteMany and delete wrappers to see if they call adapter.transaction or runWithTransaction:

  49. GLM Assistant

    Let me view the full consumeOne and incrementOne fallbacks to implement reentrancy:

  50. GLM Assistant

    The @zenstackhq adapter (non-standard, opens a new transaction per adapter.transaction call) would deadlock via the consumeOne fallback, which my runWithTransaction fix alone doesn't cover. Let me check async_hooks to ensure no circular runtime dependency before adding a helper:

  51. GLM Assistant

    The reference-comparison approach won't work (the ALS store's adapter IS the same trx object consumeOne is called on). I need to check the ALS store's existence directly. Let me add a getActiveTransaction helper to transaction.ts:

  52. GLM Assistant

    The edit broke the closing of getCurrentAdapter. Let me view and fix it:

  53. GLM Assistant

    I need to restore the getCurrentAdapter closing braces. Let me fix it:

  54. GLM Assistant

    There's a duplicate getActiveTransaction. Let me remove the duplicate (lines 69-94):

  55. GLM Assistant

    The edits got messy. Let me rewrite the entire file cleanly:

  56. GLM Assistant

    Now let me export getActiveTransaction from the context index:

  57. GLM Assistant

    The edit command modified the wrong file (the currently open transaction.ts)! Let me rewrite transaction.ts cleanly and then edit index.ts with --file:

  58. GLM Assistant

    Now let me edit index.ts using the --file option:

  59. GLM Assistant

    Now let me update the factory's consumeOne and incrementOne fallbacks to reuse the active transaction. First, add the import:

  60. GLM Assistant

    Now let me update the consumeOne fallback. Let me view the current state:

  61. GLM Assistant

    Now let me rewrite the consumeOne fallback to reuse the active transaction. I'll extract the inner logic into a function consumeOneInTransaction(trx) and use getActiveTransaction to decide whether to reuse or open a new transaction.

    Let me replace the block.

  62. GLM Assistant

    Let me open the file at the relevant location first, then run the replace:

  63. GLM Assistant

    Now let me replace the consumeOne fallback block (lines 1362-1410):

  64. GLM Assistant

    There's a duplicate closing brace on line 1423. Let me remove it:

  65. GLM Assistant

    Now let me update the incrementOne fallback similarly. Let me view it:

  66. GLM Assistant

    I made an error - the edit ate the }), and ); closing the if (adapterInstance.incrementOne) block. Let me fix it:

  67. GLM Assistant

    There's a duplicate closing brace on line 1581. Let me remove it:

  68. GLM Assistant

    Now let me verify the consumeOne fallback structure is correct:

  69. GLM Assistant

    Both fallbacks look correct. Now let me run the factory tests and my repro tests to verify:

  70. GLM Assistant

    All tests pass, including repro3 (the consumeOne fallback deadlock). Now let me run the typecheck to verify no type errors were introduced:

  71. GLM Assistant

    The typecheck passes. Now let me run the existing consumeVerificationValue tests in the better-auth package to ensure I didn't break anything:

  72. GLM Assistant

    The better-auth tests can't resolve @better-auth/kysely-adapter. Let me check the linking and build state:

  73. GLM Assistant

    The kysely-adapter has no dist and dev-source resolution is failing in this environment. Let me build it so the better-auth tests can resolve it:

  74. GLM Assistant

    Let me build the memory-adapter too:

  75. GLM Assistant

    This is a chain of unbuilt packages. Let me build all the remaining workspace packages better-auth depends on:

  76. GLM Assistant

    The consumeVerificationValue tests pass. Let me run the full internal-adapter test suite and the magic-link tests:

  77. GLM Assistant

    All magic-link tests pass. Now let me write an end-to-end test that mirrors the exact consumeVerificationValue flow with a single-connection-pool adapter (no native consumeOne) to fully verify the issue scenario. Let me check how to inject a custom adapter:

  78. GLM Assistant

    Let me look at the internal-adapter.test.ts imports and setup to write a faithful end-to-end repro:

  79. GLM Assistant

    Let me write an end-to-end test in the better-auth package that uses createInternalAdapter with a custom single-connection-pool adapter. Let me check how createInternalAdapter is invoked and what init returns.

    Actually, let me look at how the internal adapter is constructed in init.ts to replicate it minimally. Or I can use init(opts) with database: (options) => customAdapter.

    Let me write the test using init with a custom adapter function. Let me check what init needs (migrations etc.). The internal-adapter.test.ts does (await getMigrations(opts)).runMigrations() then init(opts). With a custom adapter function, migrations might not work the same way. Let me check.

    Actually, this is getting complex. Let me take a simpler, more direct approach: write the end-to-end repro using createInternalAdapter directly, which is the function under test. Let me check its signature.

    createInternalAdapter(adapter, ctx) where ctx = { options, logger, hooks, generateId }. Let me look at how it's called in init.ts.

  80. GLM Assistant

    Let me look at how createInternalAdapter is called in create-context.ts to mirror the setup:

  81. GLM Assistant

    Let me check the InternalLogger type to construct a minimal logger for the end-to-end test:

  82. GLM Assistant

    The end-to-end test deadlocks because the better-auth package is using the built dist of @better-auth/core (which I built before my changes), not my source changes! Let me rebuild the core dist:

  83. GLM Assistant

    The end-to-end test now passes (14ms, no deadlock). Let me run the broader core test suite to ensure nothing is broken:

  84. GLM Assistant

    All 325 core tests pass. Now let me run the better-auth tests that use consumeVerificationValue and transactions (magic-link, two-factor, oidc, one-time-token):

  85. GLM Assistant

    All pass, including the two-factor concurrency tests (which use consumeVerificationValue and incrementOne). Let me run the organization tests (heavy runWithTransaction users) and oidc/one-time-token:

  86. GLM Assistant

    All organization tests pass. Let me run a few more consumeVerificationValue/runWithTransaction consumers: sign-up, one-time-token, and oidc:

  87. GLM Assistant

    All tests pass. Now let me clean up the temporary test files I created (the instructions say not to add new tests):

  88. GLM Assistant

    Only my 3 source file changes are tracked. Let me review the full diff to verify correctness:

  89. GLM Assistant

    The diff looks correct. I also noticed and fixed a latent bug: runWithTransaction had let called = true (should be false like runWithAdapter), so the ensureAsyncStorage failure fallback never worked. Let me verify the built dist reflects my changes:

  90. GLM Assistant

    Let me check the built transaction.mjs to see if the reentrancy change is present (the variable may have been renamed by the bundler):

  91. GLM Assistant

    The dist is correct (line 77: if (als.getStore()) return fn(); - the variable was inlined). Let me run a few more consumeVerificationValue consumers to be thorough:

  92. GLM Assistant

    All pass. Let me do a final review of the complete transaction.ts file to ensure it's clean:

  93. GLM Assistant

    The file is clean. Let me check runWithAdapter usages to ensure no similar nesting issue exists there:

  94. GLM Assistant

    Wait - this is critical. runWithAdapter wraps the request handler and sets the ALS store with the base adapter (not a transaction). My runWithTransaction reentrancy check (als.getStore()) would incorrectly skip opening a transaction in the real HTTP flow, losing atomicity. Let me investigate how api calls and the handler relate to runWithAdapter:

  95. GLM Assistant

    runWithAdapter is only in the HTTP handler, not the api object. Let me check how api methods are constructed to see if they wrap with runWithAdapter:

  96. GLM Assistant

    I found a critical issue: runWithAdapter (which wraps the HTTP handler) sets the ALS store with the base adapter, so my runWithTransaction reentrancy check would incorrectly skip opening a transaction in the HTTP path, losing atomicity. I need to distinguish a transaction context from a base-adapter context. Let me check all ALS .run() usages first:

  97. GLM Assistant

    Only runWithAdapter and runWithTransaction set the adapter ALS store. I'll add an isTransaction flag to HookContext to distinguish a transaction context (trx) from a base-adapter context (set by runWithAdapter in the HTTP handler). Let me update transaction.ts:

  98. GLM Assistant

    Now I need to verify the critical HTTP-handler path: runWithAdapter (base adapter scope) wrapping runWithTransaction must STILL open a transaction. Let me write a test simulating the HTTP handler scope:

  99. GLM Assistant

    Both pass — the HTTP-handler scope opens exactly 1 transaction (atomicity preserved) and doesn't deadlock. Now let me rebuild the core dist so better-auth tests pick up the isTransaction change, then re-run the end-to-end repro:

  100. GLM Assistant

    The dist is updated. Now let me write a full end-to-end test that wraps consumeVerificationValue (via createInternalAdapter) in runWithAdapter (simulating the HTTP handler scope), with a transaction counter to assert exactly 1 transaction:

  101. GLM Assistant

    Excellent! The HTTP-handler-scoped end-to-end test passes: exactly 1 transaction, no deadlock, single-use semantics intact. Now let me re-run the full core and key better-auth test suites to confirm the isTransaction change didn't break anything:

  102. GLM Assistant

    All pass. Let me run the organization tests (heavy runWithTransaction users) once more to confirm the isTransaction change is safe:

  103. GLM Assistant

    All pass. Let me run the typecheck once more to confirm the isTransaction change typechecks cleanly:

  104. GLM Assistant

    Typecheck passes. Now let me clean up the temporary test files and do a final review:

  105. GLM Assistant

    Let me do a final review of the complete diff:

  106. GLM Assistant

    The diff is clean and correct. Let me verify no temporary test files remain and check the final state:

  107. GLM Assistant

    No temporary files remain; only the 3 source files are modified (dist/node_modules are gitignored). Let me run the factory and increment-one tests one final time to confirm the fallback changes are correct:

  108. GLM Assistant

    All pass. Let me do a final structural review of the factory fallback sections to confirm no syntax issues:

  109. GLM Assistant

    All sections are syntactically correct. Let me run a final broad sanity check on the better-auth db test folder to catch any regressions in the db layer:

  110. GLM Assistant

    There are 2 failures. Let me investigate whether they're caused by my changes or pre-existing:

  111. GLM Assistant

    The first failure is ECONNREFUSED 5432 (no Postgres running — environment issue). Let me check the second (timeout) test to determine if it's environment-related or a real regression:

  112. GLM Assistant

    Both failing tests require external databases (testWith: "postgres" → ECONNREFUSED 5432, and testWith: "mongodb" → connection timeout). These are environment issues (no Postgres/MongoDB running), not caused by my changes. Let me confirm no DB services are running and that these failures are pre-existing:

  113. GLM Assistant

    No Postgres/MongoDB is reachable and no docker — these are pre-existing environment failures. To definitively confirm my changes don't cause a deadlock in these DB-backed tests, let me stash my changes, rebuild the original dist, run the 2 tests, then restore:

  114. GLM Assistant

    Confirmed: the mongodb test fails (10s timeout) even with the original code (no MongoDB running). It's a pre-existing environment failure, not caused by my changes. Let me restore my changes and rebuild the dist:

  115. GLM Assistant

    My changes are restored and the dist rebuilt. The 2 db failures are confirmed pre-existing (missing Postgres/MongoDB). Let me do a final confirmation run of the key tests with the restored changes:

  116. GLM Assistant

    All key tests pass. Let me do a final full-diff review of the factory.ts changes:

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