ISSUE DESCRIPTION magic-link verify deadlocks: runWithTransaction nests…
- 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
- better-auth 1.6.11 with the
magicLinkplugin. - A database adapter whose
transactionis a real interactive DB transaction that holds a dedicated connection for its duration (e.g. the Kysely adapter, or@zenstackhq/better-auth, backed bypg). - 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.signInMagicLink({ body: { email } })-> works (single insert).await auth.api.magicLinkVerify({ query: { token } })(orGET /api/auth/magic-link/verify?token=...).
Minimal trigger: any setup where
adapter.transactionacquires 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 verificationSELECT; 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 insiderunWithTransaction-> opens transaction tx1 (BEGIN, takes the only pooled connection).- Consuming the row (
consumeOne) triggers anotherrunWithTransaction-> callsadapter.transactionagain -> transaction tx2, which tries to acquire a second connection. runWithTransactionin@better-auth/core(context/transaction.mjs) always opens a freshadapter.transaction; it does NOT checkadapterAsyncStorage.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 adapter from the ALS store. is inconsistent with this -- it doesn't reuse. - Assistant
I'll start by exploring the repository structure and locating the
runWithTransactionimplementation that's causing the nested-transaction deadlock. - Assistant
Found the transaction module; next I'll inspect
runWithTransactionand howconsumeVerificationValueuses it. - Assistant
I'll inspect
consumeVerificationValueand existing transaction tests next so the fix matches how nesting is expected to work. - Assistant
Next I'll read
consumeVerificationValueand search for existing tests around nestedrunWithTransaction. - Assistant
I'll trace the magic-link verify path and how
consumeOneinteracts with transactions. - Assistant
Interesting - there's a test specifically about nested transactions for consumeOne in prisma adapter. Let me look at the factory consumeOne fallback and the magic link verify flow, and also how with-h...
- Assistant
I'll inspect the magic-link verify handler and how the adapter's
transactionmethod behaves. - Assistant
I'll inspect how the Kysely adapter implements
transactionandconsumeOne, since that matches the deadlock setup. - Assistant
Let me look at the kysely adapter's consumeOne and transaction implementations more carefully.
- Assistant
I'll check
consumeOneWithHooksand whether hooks can start a nestedrunWithTransaction. - Assistant
I'll check how the factory handles nested caller transactions when the config disables transactions.
- Assistant
I'll find existing transaction tests and any prior discussion of making
runWithTransactionreentrant. - Assistant
I need to distinguish an active transaction from a plain
runWithAdapterstore before makingrunWithTransactionreentrant. - Assistant
I'll check call sites of
runWithAdapterso reentrancy doesn't accidentally skip a needed transaction. - Assistant
I'll check recent history of the transaction helper and
consumeOnefor context on the deadlock. - Assistant
I need to mapout whether
factorycan safely depend on the transaction context helpers. - Assistant
The issue description is very specific about the fix: I'll implement the reentrant transaction logic as described in the issue. Let me start by examining the current transaction handling code to understand the structure. I'll look at the transaction context file and related adapter patterns.
Let me check the current implementation of runWithTransaction and getCurrentAdapter: I need to understand how the async local storage is used and where the transaction flag should be added. I'll also look for where runWithAdapter is defined to understand the differences.
Let me start by exploring the codebase to find the relevant files. I'll use the file system to locate the transaction context and adapter related code. Let me check the context directory first. 1. Let me check the transaction context file. 2. Let me check the adapter types. 3. Let me check where runWithTransaction is used. 4. Let me check the consumeVerificationValue implementation. 5. Let me check the DB adapter types. 6. Let me check the K 1. Let me check the Kysely adapter implementation. 7. Let me check the Zenstack adapter implementation. 8. Let me check the tests for transaction handling. 9. Let me check the magic link verification code. 10. Let me check the better-auth core types. 11.
- Assistant
I'll check how the Zenstack adapter implements transactions, since that's the setup from the issue.
- Assistant
I'll check for circular import risks before wiring
getCurrentAdapterinto the factory. - Assistant
I'll confirm how adapter exports are wired so I don't introduce a circular dependency.
- Assistant
Implementing reentrant
runWithTransaction: reuse the active ALS transaction instead of opening a nested one. - Assistant
Now I need to update runWithTransaction itself.
- Assistant
I'll fix a missing newline and update the factory
consumeOnefallback so it reuses the active transaction instead of nesting. - Assistant
I'll export a helper so the factory's
consumeOnefallback can detect an active transaction and avoid nestedadapter.transactioncalls. - Assistant
I'll export the helper from the package index and wire it intoendre the factory fallbacks.
- Assistant
I'll rewrite the index file cleanly to remove the mangled duplicate export.
- Assistant
I'll overwrite the mangled index with a shell redirect instead.
- Assistant
Next I'll update the factory
consumeOneandincrementOnefallbacks to reuse the active transaction. - Assistant
I'll add a helper near the factory's transaction setup and update both fallbacks.
- Assistant
I'll add a helper after lazyLoadTransaction setup and before the adapter object, then use it_in consumeOne and incrementOne.
- Assistant
I'll point the
consumeOneandincrementOnefallbacks atrunInTransaction. - Assistant
I need to replace both with runInTransaction and update the FIXME comments.
- Assistant
I'll use replace for Available both occurrences.
- Assistant
I need to goto that line first.
- Assistant
Now I can replace.
- Assistant
There's a typo "nested_consumeOne" - let me fix that and also the incrementOne.
- Assistant
Now replace incrementOne页面's adapter.transaction with runInTransaction.
- Assistant
I'll align the import with the package self-reference pattern used elsewhere.
- Assistant
Need to goto line 6 first.
- Assistant
I'll write a temporary script to verify reentrancy and that
runWithAdapterstill allows real transactions. - Assistant
The script has many typos because I mangled it. Let me write a clean one carefully.
- Assistant
Good, the script was written. Let me run it with vitest or tsx/npx.
- Assistant
I'll run the temp script under vitest so workspace path aliases resolve correctly.
- Assistant
The cases timed out — likely a circular import hang. I'll check process state and try a simpler run.
- Assistant
I'll check how the package self-reference resolves under vitest — that may be what is hanging.
- Assistant
I'll check how vitest resolves
@better-auth/core/*package conditions. - Assistant
I'll run a simple existing core test first to check whether vitest itself is stuck.
- Assistant
Even a simple test timed out — I'll run vitest from the package directory with a tighter config.
- Assistant
I'll check whether type-only importsologi from the adapter are emitted at runtime and causing a cycle.
- Assistant
Factory importing context creates a Vite cycle through
adapter/index. I'll drop the factory changes and keep only therunWithTransactionreentrancy fix. - Assistant
The interface note says no new APIs — I'll remove the unused
getCurrentTransactionAdapterexport. - Assistant
I'll remove getCurrentTransactionAdapter and its export from index.
- Assistant
I'll insert the missing blank line before
runWithAdapter. - Assistant
I accidentally dropped the
runWithAdaptersignature — restoring the full file now. - Assistant
I'll write a minimal reentrancy test and confirm vitest runs again after reverting the factory change.
- Assistant
Still timing out — I'll restart with debug output to find where vitest is stuck.
- Assistant
Corepack is stuck downloading pnpm — I'll invoke the vitest binary directly instead.
- Assistant
Vitest is falling through to missing dist output for async_hooks — I'll check and build as needed.
- Assistant
I'll inspect workspace package links next —
@better-auth/coremay not be linked into node_modules. - Assistant
I'll check how existing core tests resolve package self-imports.
- Assistant
The package itself isn't linked into node_modules — I'll check the workspace layout and fix the link.
- Assistant
I'll check how the instrumentation tests resolve the package self-reference.
- Assistant
I'll add a self-link for
@better-auth/coreand rerun the reentrancy temp test. - Assistant
I'll verify the symlink target and how Node resolves the package exports.
- Assistant
I'll recalculate the symlink path — it looks like it pointed at the wrong directory.
- Assistant
I'll restore the self-linkfcntl from the repo root and rerun the reentrancy test againstd the freshly built dist.
- Assistant
Relative symlink targets are resolved from the containing directory, so they'll use
../..to point at packages/core. - Assistant
Good, symlink is correct now. Check if dist has our changes.
- Assistant
Typo in vitest command. Also the_dist has minified structure with inTransaction. Good.
- Assistant
All three reentrancy tests passed. I'll remove the temp artifacts and run closely related existing tests.
- Assistant
Final check of the diff, then submit.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.