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 locate the transaction context implementation and its tests, then reproduce the nesting behavior with a focused existing or temporary test before changing the reentrancy logic.
- Assistant
rgis unavailable, so I’ll usegrepto identify the source and relevant test layout. - Assistant
The first matches came from workspace-linked
node_modules; I’ll inspect the canonical core package and package scripts rather than edit generated/link copies. - Assistant
The defect is present exactly as reported:
runWithTransactionnever checks the current store. I’m also noting hook semantics: a nested call must share the outer store (especiallypendingHooks) and must not flush hooks early. I’ll inspect existing context tests and adapter types to build a focused reproduction without adding repository tests. - Assistant
I’ll reproduce with a temporary TypeScript script and a mock adapter whose
transactionthrows on a second acquisition. This models a one-connection pool deterministically and also checks which adapter is visible in each scope. The script will be removed afterward. - Assistant
The first run hit Corepack’s interactive download prompt (unsupported here), not the code. I’ll use the already-installed workspace binary directly; the temporary file remains because the timed-out command never reached cleanup.
- Assistant
There is no root
tsxbinary. I’ll inspect available binaries and package-manager metadata to select a noninteractive runner; if Vitest is installed, it can run a temporary test file that is then removed. - Assistant
Vitest is available in the core package. I’ll run the deterministic reproduction as a temporary test, expecting it to fail before the fix because two transactions are opened.
- Assistant
Vitest is installed at the workspace root (the prior combined listing made that ambiguous). I’ll rerun via the root binary.
- Assistant
The runner reached the source but workspace self-resolution lacks built
distunder the root invocation. Existing test scripts likely set thedev-sourceexport condition through Turbo/package scripts; I’ll inspect root scripts and Vitest configuration before proceeding. - Assistant
The config requests
dev-source, but@better-auth/coreitself is not linked at the root, so self-import resolution fails in this checkout. I can still reproduce by temporarily changing the self-import in a copied module, but the reported source-level trace already establishes the second call. I’ll implement the minimal reentrant check: after obtaining ALS, if a store exists, invokefndirectly so it inherits the active adapter and hook queue; otherwise preserve current transaction and hook behavior. I’ll also correct the apparentcalledinitialization typo so the documented no-ALS fallback remains functional, matchingrunWithAdapter. - Assistant
Python is unavailable, so I’ll apply the same small edit with the repository editor.
- Assistant
The line-range edit unintentionally removed the existing
resultdeclaration (visible in the review), so I’ll restore it before validating. - Assistant
Formatting and core typechecking pass. The store may originate from either
runWithTransactionorrunWithAdapter; the requested behavior explicitly says reuse any active adapter in the async-context store, mirroringgetCurrentAdapter, so checking store presence is appropriate. Next I’ll rerun the focused test. To make self-resolution work in this checkout, I’ll temporarily linknode_modules/@better-auth/coreto the package root, then remove both link and test. I’ll also test hook ordering so nested calls do not flush post-transaction hooks before commit. - Assistant
The temporary link target was one directory too shallow, so resolution still failed before test collection. I’ll rerun with the correct relative link target and verify it resolves before invoking Vitest.
- Assistant
Vitest’s resolver is not honoring the package self-export even with a link, likely because it canonicalizes the real path before package lookup. For focused runtime verification only, I’ll temporarily rewrite the source’s self-import to its equivalent relative module, run the test, and immediately restore the original import. This does not alter the submitted diff.
- Assistant
The focused test now passes: only one transaction is acquired, the active transaction adapter remains visible, and the nested hook runs only after the outer commit. I’ll run the full core test project with the same temporary import workaround, then restore it, followed by final typecheck/format/diff inspection.
- Assistant
The core suite executed 306 tests successfully; three suites failed only during import because this checkout lacks workspace self-links for other core subpath exports (
async_hooksandinstrumentation), unrelated to the change. To keep the patch narrowly scoped, I’ll revert the incidentalcalledinitialization correction—the deadlock fix only needs the store check—and run final static validation. - Assistant
The literal replacement was ambiguous because
runWithAdapterhas the same declaration. I’ll target the exact line inrunWithTransaction, then re-run the final checks.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.