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
Let me start by exploring the repository structure and understanding the codebase.
Assistant
Now let me look at how
consumeVerificationValueworks.Assistant
Now let me look at
consumeOneWithHooks:Assistant
Now let me look at the magic-link verify flow:
Assistant
Let me understand the flow now. The
consumeVerificationValuecallsrunWithTransactionwhich opens a transaction. Inside that transaction, it callsconsumeOneWithHookswhich callsconsumeFn()which callstxAdapter.consumeOne.But the issue says "Consuming the row (consumeOne) triggers another runWithTransaction". Let me check the
consumeOneadapter implementation - does it callrunWithTransaction?Let me check the with-hooks for createOne/updateOne etc., and whether consumeOne in with-hooks calls runWithTransaction.
Assistant
Let me check internal-adapter.ts line 124 - that's the
consumeOneadapter method.Assistant
Now let me look at the adapter's
consumeOneimplementation to see if it callsrunWithTransaction:Assistant
Let me check the adapter's
consumeOneimplementation in the kysely adapter:Assistant
Let me look at the kysely-adapter's consumeOne to see if it uses runWithTransaction.
Assistant
Let me look at the full magic-link verify flow:
Assistant
Let me check the prisma-adapter consumeOne, which the issue mentions tests:
Assistant
Let me look at the prisma-adapter test that checks for nested transactions:
Assistant
Let me look at the transaction tests:
Assistant
Let me check the git log to understand the recent changes:
Assistant
Let me check where
runWithAdapteris used to understand the relationship:Assistant
This is critical -
runWithAdapterwraps the entire request handler and sets a store with the regular adapter. Let me check howapicalls work:Assistant
Now I understand the architecture. The key insight:
runWithAdapter(which wraps HTTP handler requests) sets an ALS store with the regular (non-transaction) adapter. So I can't just check forals.getStore()truthiness - I need to distinguish between a store set byrunWithAdapter(no real transaction) and one set byrunWithTransaction(real transaction). Let me add aninTransactionflag to theHookContexttype.Assistant
Now let me look at the compiled/built
transaction.mjsreferenced in the issue, to confirm the published version:Assistant
Let me write a reproduction test first. Let me create a test that simulates a single-connection pool adapter:
Assistant
Let me look at the existing test setup for context and adapters:
Assistant
Let me look at the DB adapter type to understand the interface for creating a mock:
Assistant
Let me look at the
transactionmethod on the adapter to understand its signature.Assistant
Now I understand the structure well. Let me create a reproduction test that simulates a single-connection pool adapter where nested transactions deadlock:
Assistant
There's a package resolution issue. Let me check how the existing tests in the core package run - perhaps they need the package to be built, or there's a vitest config that handles the aliasing.
Assistant
The
dev-sourcecondition resolves to source files. But the SSR config hasconditions: ["dev-source"]. The issue is that the package@better-auth/core/async_hooksneeds to be resolved. Let me check the root vitest config more fully and how other tests import from@better-auth/core. The issue is that the test runs but the import of@better-auth/core/async_hooksfails because the package isn't resolving through node_modules.Let me check if there's a node_modules/@better-auth/core symlink.
Assistant
The
@better-auth/coreis the workspace package itself. Let me check whether it's self-linked:Assistant
Let me try running an existing core test to see if it works:
Assistant
Let me check if the better-auth package tests work (they import
@better-auth/core):Assistant
The core package's own tests can't resolve
@better-auth/core/*self-references. Let me check if dist exists or needs building:Assistant
Let me build the core package to create the dist, which should help resolve the self-references. But first, let me try a simpler approach - create a self-link symlink:
Assistant
The symlink target is wrong. Let me fix it:
Assistant
Let me check if the better-auth package tests resolve
@better-auth/corecorrectly:Assistant
Even better-auth tests fail with the
dev-sourcecondition issue. Thedev-sourcecondition isn't being applied. Let me build the core package so the default dist exports resolve:Assistant
The build timed out. Let me investigate why
dev-sourceisn't applied - let me check the better-auth vitest config:Assistant
The
ssr.resolve.conditions: ["dev-source"]is set at the root. In vitest 4, thessrconfig might apply only whenenvironmentis set to node andssrmode is active. Actually, in vitest,ssroption enables SSR interop. By default, vitest transforms files in the test environment (node). Thessr.resolve.conditionsapplies to SSR-transformed modules.Hmm. Let me check the vitest version and whether
ssr.resolve.conditionsis the right way. Actually, maybe the problem is that vitest 4 requirestest.server.deps.inlineorresolve.conditionsat top-level.Wait - maybe this whole test setup is just broken in this environment and normally CI uses a specific setup. Let me check if there's an existing way to run the core tests. Let me look at the root package.json scripts.
Assistant
Let me try configuring vitest to inline workspace deps so vite's resolver (with dev-source condition) handles them:
Assistant
Let me check the async_hooks module and try a Node-based approach with the dev-source condition:
Assistant
Let me try a vitest config with explicit aliases for the self-references:
Assistant
Let me check what global.ts and db/adapter import to know all aliases needed:
Assistant
Let me rewrite the tmp config as a standalone config and run from within the core package:
Assistant
I've reproduced the deadlock. Now let me implement the fix. Let me open the transaction.ts file:
Assistant
Now I understand the full picture. Let me implement the fix. First, update the
HookContexttype to add aninTransactionflag:Assistant
Now update
runWithAdapterto setinTransaction: false:Assistant
The indentation on line 68 got messed up. Let me fix it:
Assistant
Let me verify the actual indentation with cat -A:
Assistant
Line 68 now has 3 tabs but should have 4 (to match the
trybody). Let me fix with sed:Assistant
Now let me update
runWithTransactionto be reentrant. Let me edit the function:Assistant
Now let me run the reproduction test to confirm the fix works:
Assistant
Both tests pass. Let me verify the original 1.6.11 structure to fully understand the nesting. Let me check the commit that introduced this:
Assistant
Let me check if there's a fallback
consumeOneimplementation in better-auth that usesrunWithTransaction:Assistant
The fix is correct. Now let me verify I'm not breaking existing behavior. Let me check the organization adapter's
runWithTransactionusage to ensure reusing active transactions is safe:Assistant
Let me check the better-auth internal-adapter tests for consumeVerificationValue coverage:
Assistant
Let me check all
@better-auth/core/*subpath imports used by the better-auth package to set up aliases:Assistant
Let me generate a comprehensive vitest config with aliases for all
@better-auth/coresubpaths so I can run the better-auth tests:Assistant
Progress - the core resolution works now. It fails on
@better-auth/kysely-adapter. Let me add aliases for the other workspace adapters too:Assistant
The
dev-sourcecondition isn't applied in vitest 4'sssr.resolve.conditions, butresolve.aliasworks. Let me add aliases for the adapters:Assistant
Let me check what workspace packages are linked in better-auth's node_modules:
Assistant
telemetryis symlinked - the issue is purely thedev-sourcecondition not being applied. Let me add the conditions to my tmp config:Assistant
Now
better-callfails becausessr.noExternalis too aggressive. Let me useresolve.conditionswith the dev-source condition plus standard fallback conditions instead:Assistant
Let me check if
better-callis properly installed and resolvable:Assistant
better-callresolves via Node fine - the SSR pipeline needs standard conditions too. Let me combine everything with both dev-source and standard conditions:Assistant
Let me check
better-call's package.json exports:Assistant
better-calldeclaresdev-source: ./src/index.tsbut may not shipsrcin the published package. Let me check:Assistant
better-calldoesn't shipsrc, sodev-sourcebreaks it. The root cause is thedev-sourcecondition not being selectively applied. Let me check what workspace package subpaths better-auth imports (besides core):Assistant
Good - only root imports. Let me rewrite the config: alias all workspace packages to their
src/index.ts, and use standard conditions only (nodev-source) so published deps likebetter-callresolve to their dist:Assistant
Let me check the turbo task dependencies to see if tests depend on a build:
Assistant
The
testtask depends on^build- CI builds packages first. Thedev-sourcecondition inbetter-call's exports points to non-existentsrcin the published package. Let me find all published deps withdev-sourceexports that lacksrc, and alias them to dist:Assistant
Let me find which of the published deps have
dev-sourcein their exports (those would break with dev-source condition). Let me check better-call and @better-fetch/fetch.Assistant
Let me read the package.json directly via filesystem:
Assistant
Only
better-callhas the problematicdev-source(no src). Let me find allbetter-callsubpaths imported and alias them to dist:Assistant
Only
better-callis problematic. The config that got furthest wasssr.resolve.conditions: ["dev-source"]+ssr.noExternal(it resolved all@better-auth/*packages and core self-references via dev-source). It only failed onbetter-call. Let me addbetter-callaliases to dist:Assistant
Excellent! The internal-adapter tests pass (51 tests), including all
consumeVerificationValuetests! Now let me run the magic-link tests to verify the verify flow:Assistant
All 18 magic-link tests pass. Now let me enhance my core repro test to cover the important edge cases: hook draining and error propagation in the reentrant case. Let me update it:
Assistant
Now let me rewrite the repro test to also cover hook draining and error propagation in the reentrant case:
Assistant
All 4 tests pass. Now let me run a broader set of better-auth tests that exercise
runWithTransactionto ensure nothing breaks. Let me run sign-up, organization, and two-factor tests:Assistant
Sign-up and internal-adapter tests pass. Let me run the organization and two-factor tests which heavily use
runWithTransaction:Assistant
Organization tests pass (100 tests). Let me run the one-time-token, email-otp, and passkey tests which also use
consumeVerificationValue:Assistant
All passing. Let me run the two-factor tests too:
Assistant
All tests pass. Now let me check the git status to see what I've changed and clean up temporary files:
Assistant
The git status confirms only
transaction.tsis modified (my fix). The temp files are untracked. Per the instructions, I must not add new tests, so let me remove all temporary files:Assistant
Only
transaction.tsis modified. Let me review the final diff of my fix:Assistant
The diff looks clean. Let me verify the
calledflag change is correct by comparing withrunWithAdapter's pattern - the originallet called = truemade the.catchfallback dead code (a bug). Let me also check whether the repo requires a changeset for fixes:Assistant
Let me check the changeset config and the package name used for core:
Assistant
Let me create a changeset for this fix following the repo convention:
Assistant
Let me do a final review of the complete transaction.ts file:
Assistant
Let me check if there are any other places that create the ALS store that need the
inTransactionfield (since I made it required):Assistant
Both ALS store creation sites are updated. Let me run a TypeScript typecheck on the core package to ensure no type errors:
Assistant
Typecheck passes. Let me confirm the final git status and diff:
Assistant
Let me check if any tests exercise the
ensureAsyncStoragerejection/fallback path that mycalledchange might affect:Assistant
No tests depend on the ALS-failure path. My
calledchange (fixing the dead fallback code to matchrunWithAdapter) is safe. Let me do a final review of the complete file:Assistant
The fix is complete and coherent. Let me verify no other package vendors its own copy of
runWithTransactionthat needs the same fix:Assistant
Let me check the
factory.tsdirectadapter.transactioncalls to see if they could nest within an active transaction:Assistant
This is the fallback
consumeOnefor custom adapters. The FIXME comment explicitly notes the "already inside a transaction" problem. Let me understand whatadapterthis closes over:Assistant
Let me check what
adapterthe fallbackconsumeOneuses (trx vs base):Assistant
This factory fallback
consumeOne(for custom adapters without a nativeconsumeOne) callsadapter.transactiondirectly and is a separately documented limitation (theFIXME(consume-one-nested-transaction)comment) deferred to a breaking adapter-contract change. First-party adapters (kysely/drizzle/prisma) have nativeconsumeOnethat already reuses the in-flight transaction, and the reported@zenstackhqcase uses a nativeconsumeOnethat goes throughrunWithTransaction(per the issue trace "consumeOne triggers another runWithTransaction"). My fix torunWithTransactiondirectly resolves the reported nesting, which is exactly the "Expected" fix requested.Let me do a final confirmation of the complete diff and that no stray temp files remain:
Assistant
The diff is clean and focused. Let me do one final verification by recreating a minimal repro test to confirm the fix resolves the deadlock, then clean it up before submitting:
Assistant
Both tests pass. The fix is confirmed. Now let me clean up the verification files:
Assistant
Both changes are clean. Let me verify the
calledflag change is a genuine bug fix by checking git history:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.