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 repository structure and locate
runWithTransaction, its async-context storage, and related tests. Then I’ll implement reentrant transaction reuse consistently withgetCurrentAdapter, run focused tests (and broader relevant tests if practical), and review the diff for edge cases. - Assistant
rgis unavailable in this environment, so I’ll usegrep/findinstead. The repository is a pnpm monorepo; I’m narrowing the search to the core package and transaction-related tests before editing. - Assistant
The implementation confirms the bug:
runWithTransactionalways invokesadapter.transaction, while the ALS store already contains the active transaction adapter and hook queue. The fix will short-circuit tofn()when a store exists, preserving the outer transaction and ensuring nested hooks remain owned by the outer scope. I’ll also align the fallback flag withrunWithAdapterso storage initialization failures do not incorrectly suppress execution. - Assistant
The first edit attempt could not run because this container lacks Python; no files were changed. I’ll apply the same targeted change with Node, then inspect and typecheck the core package.
- Assistant
The change is now in place. It checks the current ALS store before creating a hook queue or calling
adapter.transaction; nested calls therefore execute in the existing transaction context. I’ll run the core typecheck and context-focused test suite, then a small temporary runtime check using a one-connection-style adapter to verify only one transaction is opened. - Assistant
The validation command timed out because Corepack attempted an interactive pnpm download, so no tests ran. I’ll avoid that prompt by using the repository’s locally installed binaries (or
npx-style direct tools), first checking what is available. - Assistant
TypeScript validation passed. The focused Vitest invocation reached the test runner but failed during module resolution because this checkout lacks the workspace package link for
@better-auth/core/async_hooks; that is an environment setup issue rather than a test failure. I’ll inspect the test configuration and run the core package’s configured test command if possible, then use a temporary compiled/imported check if the workspace link remains unavailable. - Assistant
The configuration review exposed an important edge case: every auth handler is wrapped in
runWithAdapter, which also populates the same ALS store. Therefore checking merelyals.getStore()would incorrectly suppress the outermost transaction. I’ll add an internal transaction marker to the store, set only byrunWithTransaction, and check that marker; nested transaction calls reuse it while ordinary request adapter context still starts a transaction. - Assistant
The marker-based fix typechecks and formats cleanly. It preserves the distinction between request scope and transaction scope, and the outer transaction’s existing hook queue remains authoritative. I’ll run the package build and a temporary behavioral script against the built module, then inspect final status.
- Assistant
The build attempt could not run because
tsdownis not linked into the root.bin; no source change resulted from that failure. The core typecheck already passed. I’ll locate the package-local executable (or skip build if unavailable), and ensure the working tree contains only the intended source edit. - Assistant
Validation is complete: the core TypeScript project typechecks, the core build succeeds, and the temporary one-connection behavioral check confirms nested calls open exactly one transaction and see the transaction adapter. The focused Vitest test could not load due to the missing workspace self-link, but this was unrelated module-resolution setup. The final diff is limited to the transaction context implementation, with no test files changed. I’ll now submit.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.