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 explore the repository structure to understand the codebase and find the relevant files.
Assistant
Now let me look at how
runWithTransactionis called, and theconsumeVerificationValuefunction.Assistant
Let me look at
consumeOneWithHooksand the otherrunWithTransactioncall at line 1329.Assistant
So
consumeOneWithHooksitself doesn't callrunWithTransactionagain. Let me re-read the issue more carefully.The issue says:
internalAdapter.consumeVerificationValueruns insiderunWithTransaction-> opens transaction tx1.- Consuming the row (
consumeOne) triggers anotherrunWithTransaction-> callsadapter.transactionagain -> transaction tx2.
Let me look at the adapter's
consumeOne- maybe it has hooks that call runWithTransaction. Let me look at line 1329 which is another runWithTransaction call.Assistant
Let me look at the magic-link plugin code and the verify path.
Assistant
Let me check the
consumeOneadapter implementation and whether it nests transactions.Assistant
Let me look at how the transaction adapter is built and whether
consumeOneon the transaction adapter callsrunWithTransaction.Assistant
Now let me understand the
consumeOnefallback more. WhentxAdapter.consumeOneis called,txAdapteris the transaction adapter (trx). The factory'sconsumeOneusesadapter.transaction(the outeradapter, nottrx). Wait, let me check. The factory builds theadapterobject. TheconsumeOnemethod is defined on this adapter. WhentxAdapter.consumeOneis called -txAdapteris the transaction adapter (thetrxreturned byadapter.transaction(cb)). Let me check howtrxis structured - does it have its ownconsumeOne?Let me look at
createAsIsTransaction.Assistant
Let me check the Kysely adapter for native
consumeOneimplementation.Assistant
Here's the nested transaction! In the Kysely adapter's
consumeOne:For non-MySQL (e.g., PostgreSQL), it uses
deleteWithReturning(query)wherequeryis built usingdb.deleteFrom(...). Wait, butdbhere - is it the transaction connection or the base db?Let me look at how this adapter wraps methods. The
dbvariable - let me check how the kysely adapter handlesinTransactionand whatdbis. There's a reference toinTransactionin the MySQL branch:inTransaction ? claimFromTransaction(db) : db.transaction().execute(claimFromTransaction). Sodbmay already be a transaction connection. For the non-MySQL path, it usesdb.deleteFrom(...)directly. So ifdbis the outer transaction, it's fine - it reuses the transaction. Ifdbis the base db, it would create a new connection... butdeleteFromdoesn't open a transaction.Wait, but the kysely adapter's
consumeOnefor PostgreSQL doesn't open a transaction itself - it just does a on . So is whatever connection is in scope. If we're inside the outer transaction, then should be the transaction connection.Assistant
So the kysely adapter's
consumeOnefor PostgreSQL usesdb.deleteFrom(...)directly, wheredbis the kysely instance passed in. The kysely adapter is wrapped viacreateCustomAdapter(db, inTransaction). Let me check how thetransactionis configured - does it create a newcreateCustomAdapterwith the transaction connection?Let me look at the kysely adapter's
transactionconfiguration.Assistant
Now I understand the kysely adapter structure. Let me look at the git history to understand the 1.6.11 changes.
Assistant
Let me look at the magic-link consume change (#9572) and the original verify code.
Assistant
Let me see the part where
runWithTransactionwas added toconsumeVerificationValue.Assistant
Let me look at the full
consumeOnefactory method to understand its transaction handling.Assistant
OK so the factory
consumeOne:- If
adapterInstance.consumeOneexists -> call it directly (no nested transaction for the kysely adapter, which reusesdb/trx). - Else -> fallback:
adapter.transaction(async (trx) => {...})- this is a NESTED transaction on the BASE adapter.
So for the @zenstackhq adapter, if it doesn't implement native
consumeOne, the factory fallback opens a nested transaction -> deadlock.Now the issue's requested fix is to make
runWithTransactionreentrant. But the factory fallbackconsumeOnecallsadapter.transactiondirectly, not . So the fix to alone wouldn't fix the factory fallback path.- If
Assistant
Let me look at the imports and structure of the factory.ts to see what's available.
Assistant
Let me check how
runWithAdapterandrunWithTransactioninteract - whetherrunWithTransactionis ever called withinrunWithAdapter.Assistant
So
runWithAdapterwraps the entire request handler inbase.ts, setting the ALS store with the base adapter. This meansrunWithTransactioncan't simply check whether a store exists - it must distinguish between a store set byrunWithAdapter(base adapter, needs a new transaction) and one set byrunWithTransaction(atrx, should be reused). Let me examine the adapter types.Assistant
The
DBTransactionAdapterisOmit<DBAdapter, "transaction">- a transaction adapter has notransactionmethod. But the factory-wrapped adapters always have atransactionmethod (as-is fallback), so that's not a reliable distinguisher. Let me look at howgetCurrentAdapteris used and check the context/index exports.Assistant
Let me look at the existing tests for transactions to understand expected behavior.
Assistant
Let me look at the magic-link test to understand the test setup.
Assistant
Let me look at how tests run and check the test-instance setup, then write a reproduction.
Assistant
Let me write a reproduction script at the
runWithTransactionlevel to confirm the deadlock.Assistant
Let me fix the type issue in the reproduction.
Assistant
The package uses self-referencing imports. Let me check the vitest config.
Assistant
There's a root vitest.config.ts with
ssr.resolve.conditions: ["dev-source"]which resolves from source. So the self-referencing import@better-auth/core/instrumentationshould resolve via thedev-sourcecondition. Let me check the exports forinstrumentation.Assistant
The exports exist. The issue is that running vitest from the root with the workspace config picks up the
dev-sourcecondition. Let me run from the root.Assistant
Let me check how existing factory tests are run and whether the package is linked.
Assistant
Even the existing factory test fails when run directly. Let me check how tests are normally run in this workspace.
Assistant
Let me verify the self-reference resolution and check the root vitest setup more closely.
Assistant
Let me check the root node_modules for the package self-link and the dist.
Assistant
node_modules/@better-authdoesn't exist and dist is empty. The self-reference needs thedev-sourcecondition or a build. Let me check the turbo test task dependencies and whether building is needed.Assistant
Tests require a build first. Let me build the core package.
Assistant
Let me check how packages link each other and whether building is feasible in the background.
Assistant
Let me run the build in the background and poll for completion.
Assistant
Build completed. Now let me run the existing factory test and my reproduction test.
Assistant
Now let me run my reproduction test to confirm the deadlock.
Assistant
The test passed, meaning no deadlock occurred. Let me check where
transactionshould be configured in the factory options.Assistant
transactionbelongs insideconfig, not at the top level. Let me fix my reproduction.Assistant
The deadlock reproduces. Now let me implement the fix in
runWithTransaction. Let me open the transaction.ts file.Assistant
Now I understand the full picture. Let me implement the fix. First, I'll modify
transaction.tsto makerunWithTransactionreentrant by adding anisTransactionflag to theHookContextand a helper to get the active transaction adapter.Assistant
Now let me add the
getActiveTransactionAdapterhelper aftergetCurrentAdapter:Assistant
Now let me update
runWithTransactionto be reentrant:Assistant
Let me set
isTransaction: falseexplicitly inrunWithAdapterfor clarity.Assistant
The indentation on line 88 looks off. Let me check the actual bytes.
Assistant
The tabs are correct. Now let me export
getActiveTransactionAdapterfrom the context index.Assistant
Now let me update the factory fallback
consumeOneandincrementOneto reuse the active transaction. Let me view theconsumeOnefallback again with exact line numbers.Assistant
Now let me refactor the factory fallback
consumeOneandincrementOneto reuse the active transaction. First, add the import.Assistant
Let me check for circular dependency concerns. The
context/transaction.tsimportsimport type { DBAdapter, DBTransactionAdapter } from "../db/adapter";(type-only) andimport { __getBetterAuthGlobal } from "./global";andimport { getAsyncLocalStorage } from "@better-auth/core/async_hooks";.If I add
import { getActiveTransactionAdapter } from "../../context/transaction";to factory.ts, then:- factory.ts (db/adapter) -> context/transaction.ts (value import)
- context/transaction.ts -> (type-only) db/adapter (erased), async_hooks, global
So no runtime cycle. Good. Let me add the import.
Actually wait, let me double-check: does
context/transaction.tsget loaded beforefactory.tsneeds it? The import is at module top, so when factory.ts is imported, it imports context/transaction.ts. context/transaction.ts imports async_hooks (self-ref) and global. No dependency back to factory. So fine.Let me add the import after the existing imports.
Assistant
Now let me refactor the
consumeOnefallback to reuse the active transaction.Assistant
There's a duplicate closing brace at line 1421. Let me fix it.
Assistant
Let me remove the duplicate closing brace at line 1421.
Assistant
Now let me do the same for the
incrementOnefallback.Assistant
Same duplicate brace issue. Let me remove the duplicate at line 1579.
Assistant
Let me run the reproduction test and the existing core factory/increment tests.
Assistant
My repro test now passes. Let me add a test for the
consumeOnefallback reusing the active transaction, to validate that part of the fix.Assistant
The
trxin my test is a raw custom adapter without the factory'sconsumeOne. Real adapters wraptrxvia the factory. Let me rewrite the test to properly simulate an adapter (like@zenstackhq) whose transaction-scoped adapter opens a nested transaction on the base.Assistant
The model naming (plural) means
findManylooks up the wrong key. Let me normalize the model key in the test's custom adapter.Assistant
The replace didn't match because of indentation? Let me just rewrite the createCustomAdapter findMany/deleteMany to use a normalized key. Let me open the file and edit the relevant lines.
Assistant
Let me update the custom adapter to normalize the model key (strip trailing 's') so it works with
usePlural.Assistant
Now let me check the verification default field naming and update the test's stored row to match.
Assistant
With
options.verification?.fields?.identifier || "identifier", and I didn't setfields.identifier, so it's "identifier". Good. So the where field "identifier" stays "identifier". And the value "tok" stays "tok" (no customTransformInput). So the row{ id: "v1", identifier: "tok" }should match.But wait, the model name. With
usePlural: trueand modelName "verification",getModelName("verification")returns "verifications" (pluralized). ThengetDefaultModelNamereturns "verification" (the modelName). Wait, let me check. TheconsumeOneusesunsafeModel = getDefaultModelName(unsafeModel). Let me check getDefaultModelName vs getModelName. The fallback passesmodel: unsafeModelto findMany.unsafeModelaftergetDefaultModelNameis the modelName "verification". So findMany gets model "verification" -> key "verification" (strip trailing s, no change) -> returns the row. Good.Wait, but
getModelNameis used for (the display/log name) and for . Let me verify the consumeOne code:Assistant
The
deleteManyfilter logic for theidclause is inverted. Let me fix it to proper eq semantics.Assistant
The edit mangled the deleteMany block. Let me rewrite it cleanly.
Assistant
Both tests pass. Let me verify they actually catch the bug by temporarily reverting the fallback fix to confirm the test fails without it.
Assistant
That sed didn't work due to multiline. Let me just do a quick edit to force
adapter.transaction(consumeInTransaction)always (not reuse), run the test, confirm failure, then restore from backup.Assistant
Let me make a temporary verification by forcing the consumeOne fallback to always open a nested transaction.
Assistant
python3 isn't available, so the patch didn't apply. Let me use node to patch and verify.
Assistant
The test correctly catches the deadlock when the fix is removed (
counters.nestedbecomes 1, indicating a deadlock attempt). Now let me restore the fixed version.Assistant
Now let me rebuild the core package so the
better-authpackage tests (which use the dist) pick up the changes, then run the relevant tests.Assistant
The dist is built with my changes. Now let me run the better-auth magic-link and internal-adapter tests.
Assistant
The better-auth tests need other packages' dist built. Let me check what the test instance imports and build the needed packages.
Assistant
Let me build the needed adapter packages in the background.
Assistant
Now let me run the magic-link test.
Assistant
All 18 magic-link tests pass. Let me run the internal-adapter tests and the secondary-storage magic-link test.
Assistant
This test imports
better-auth/client/pluginswhich resolves to thebetter-authpackage dist (not built). Let me see the full error.Assistant
The
test/package needs thebetter-authpackage dist. Let me build it in the background.Assistant
better-auth dist is built. Let me run the secondary-storage test and the broader test suite for affected areas.
Assistant
Let me run the broader affected test suites - core db tests, sign-up, organization, and the with-hooks tests.
Assistant
with-hooks.test.ts doesn't exist. Let me find the with-hooks test. Let me run the sign-up test and organization adapter test which use runWithTransaction.
Assistant
There are 2 timeouts in db.test.ts. Let me investigate whether they're caused by my change. Let me run db.test.ts alone.
Assistant
The "forced UUID on postgres" test fails with
ECONNREFUSED ...:5432- it requires a Postgres DB not available here. Let me check the "coerce string" test which timed out.Assistant
The two failures are environmental (require Postgres
:5432and MongoDB, which aren't available here) — not caused by my change. The organization tests all passed (234 passed). Let me run the OIDC/OAuth provider tests that exerciseconsumeVerificationValueandrunWithTransaction.Assistant
The oauth-provider token tests pass. Let me check other code paths that use
consumeVerificationValueandrunWithTransactionto ensure broad coverage.Assistant
Let me run the key plugin tests that use
consumeVerificationValue/runWithTransaction.Assistant
All pass. Let me run the full core db and context test directories to ensure nothing broke in core.
Assistant
All core tests pass. Now let me remove my temporary reproduction test file (per the instructions not to add new tests to the repo) and add a changeset following the repo convention.
Assistant
Let me check the package name used for core in changesets/CHANGELOG.
Assistant
The core package name is
@better-auth/core. Let me create a changeset for this fix.Assistant
Let me verify the dist reflects the factory fallback changes and confirm no leftover repro files.
Assistant
The dist reflects my changes and is gitignored (not in git status). Let me review the full source diff.
Assistant
I notice the
runWithAdapterline indentation is now 3 tabs but should be 4 (to align insidetry). Let me verify and fix.Assistant
The
result = ...line should be at 4 tabs (insidetry). Let me fix the indentation.Assistant
Now let me review the factory.ts diff for correctness and indentation.
Assistant
The diff looks clean. Let me run the linter/formatter on the changed files to ensure conformance.
Assistant
Biome wants the import sorted. Let me apply the safe fix.
Assistant
Lint passes now. Let me verify the transaction.ts is still correct after biome's formatting.
Assistant
Biome reformatted the
als.runcall. Let me rebuild core to keep dist in sync, then re-run the key tests.Assistant
All 112 tests pass. Let me check the build log for any circular dependency warnings from my new import.
Assistant
No circular dependency warnings, and the build's dts generation (type-checking) succeeded. Let me do a final review of the complete diff and git status.
Assistant
The changeset is untracked and
git diff(used by submit) doesn't include untracked files. Let me mark it as intent-to-add so it appears in the diff.Assistant
The changeset now appears in the diff. Let me do a final review of the complete transaction.ts to confirm the final state is correct.
Assistant
Everything looks correct. Let me run a couple more affected route tests (
update-user,password) that userunWithTransaction.Assistant
All tests pass. Let me do a final confirmation that all changes appear in
git diff(what submit will capture).
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.