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 inspect the transaction context implementation, related tests, and repository conventions first. Then I’ll add the smallest reentrancy fix and validate it with focused and existing tests, including a transaction-count/deadlock-style reproduction if feasible.
- Assistant
The initial scoped search returned no matches, so I’ll enumerate package structure and search the entire repository (including possible renamed TypeScript sources).
- Assistant
ripgrepis unavailable in this environment. I’ll usegrepand inspect the core context directory directly. - Assistant
I found the implementation but no dedicated transaction test in the core package. I’ll read the full module, global storage typing, package scripts, and the magic-link consumption call path to ensure the fix preserves fallback behavior for adapters without transaction support.
- Assistant
The defect is exactly as reported:
runWithTransactionnever checks the active ALS store, whilegetCurrentAdapterdoes. The correct nested behavior is to invokefndirectly in the existing context; this also keeps nested after-transaction hooks on the outer transaction’s queue so they run only after the actual commit. Before editing, I’ll run a small temporary reproduction showing that nested calls currently invoke the adapter’s transaction method twice. - Assistant
The reproduction did not run because Corepack attempted an interactive pnpm download (which this environment disallows), not because of the code. The temporary file remains. I’ll inspect available local executables and package-manager metadata, then run it via a noninteractive local tool if available.
- Assistant
Corepack is now provisioned noninteractively. I’ll adjust the temporary script’s purely test-side type assertion and rerun it; this models the nested acquisition count without intentionally hanging the process.
- Assistant
Neither Python nor
vite-nodeis installed. Vitest is available, so I’ll convert the temporary reproduction into a transient test, run it, and remove it immediately afterward; it will not be part of the submitted changes. - Assistant
The first transient test was malformed because the wrapper was inserted before its imports; it was removed successfully and did not exercise the implementation. I’ll recreate it correctly with imports first and establish the pre-fix behavior.
- Assistant
The package-local Vitest invocation cannot resolve the package’s self-reference (an environment/configuration issue); repository tests are intended to run from the workspace root. Static inspection and the transaction callback show the pre-fix double acquisition unambiguously. I’ll now add the active-store early return before creating a hook queue or invoking
adapter.transaction. This deliberately reuses both the active transaction adapter and its pending-hook lifecycle. - Assistant
The editor replacement duplicated the existing hook declaration; I caught this in the diff and will remove the duplicate. One semantic edge case needs checking:
runWithAdapteralso creates the same store, likely to mark an already supplied transactional adapter. I’ll inspect its call sites before deciding whether any store is sufficient (matchinggetCurrentAdapter) or whether transaction contexts need an explicit flag. - Assistant
A crucial edge case emerged:
runWithAdapterwraps every auth request with the base adapter, so treating any store as transactional would silently disable top-level transactions. I’ll explicitly mark ALS contexts as transactional. A normal request context remains nontransactional and opens a transaction; a nestedrunWithTransactionsees the marker and reuses it. This is more robust than comparing adapter object identity, since adapters may return the same object for a transaction. - Assistant
Two sequential line-number edits shifted the file and malformed the
.thencallback, and the type replacement left an extra brace. The diff check exposed this before testing. I’ll repair those exact regions, then run formatting/type checks before any behavioral validation. - Assistant
I’ll restore the missing callback opener and remove the stray brace. I’ll also format the ALS payloads in the repository’s multiline style to keep lint clean.
- Assistant
The line-based editor applies each change immediately, so later stale line numbers compounded the corruption. Rather than patching a damaged file, I’ll restore this single file from Git and apply deterministic exact-string replacements with Node. This preserves all original code except the intended context marker and reentrant branch.
- Assistant
The deterministic replacement matched the first
.thenblock—runWithAdapter—rather thanrunWithTransaction; the diff makes that visible. I’ll move the early-return branch to the correct function using a replacement anchored onlet called = true. The context marker additions themselves are correct. - Assistant
The final diff now has the intended shape. I’ll validate three behaviors in one transient root-level Vitest run: a transaction still starts inside the ordinary request adapter context, a nested transaction does not acquire again, and
getCurrentAdapterremains the transaction adapter throughout nesting. - Assistant
The behavioral test still cannot load because this checkout lacks the
@better-auth/coreself-link required bytransaction.ts; this is unrelated to the change and occurs before test collection. I’ll use a temporary Vitest config that aliases only that self-import to its source file, rerun the same transient test, and remove both temporary files. - Assistant
The focused reproduction now passes: the ordinary request context opens exactly one transaction, and the nested call reuses its transaction adapter. I’ll run the core TypeScript check and the existing core test suite with the same temporary self-import alias if needed. I’ll also run the repository formatter/linter against the changed file.
- Assistant
TypeScript and Biome checks pass. I’ll now run all existing
@better-auth/coretests using the temporary alias configuration (the repository’s missing package self-link otherwise prevents imports from resolving in this environment), then inspect final status/diff and ensure no temporary files remain. - Assistant
The core suite executed 313 tests successfully; two suites failed during import because the temporary config also needs the checkout’s missing
@better-auth/core/instrumentationself-link. No tests failed. I’ll add that second alias and rerun the two blocked suites (rather than rerunning all passing tests), then perform final repository hygiene checks.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.