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 the transaction context implementation and related tests. Then I’ll reproduce the nested transaction behavior with the smallest existing test harness, patch it, and run the relevant test suite.
- Assistant
ripgrepis unavailable, so I’ll usegrep/findto locate the implementation and inspect package conventions before editing. - Assistant
The core implementation is isolated in
packages/core/src/context/transaction.ts. I’ll inspect it, its async-storage abstraction, and nearby test patterns. Per the environment constraint, I will not add or modify repository tests; I’ll use a temporary reproduction script and remove it afterward. - Assistant
runWithTransactionunconditionally invokes the base adapter’stransaction, while the same ALS store already identifies the active adapter and owns the pending post-transaction hook queue. The correct reentrant path should returnfn()immediately when a store exists, preserving the outer transaction’s hook lifecycle. Before patching, I’ll inspect adapter types and allrunWithAdapteruses to confirm that any active adapter context—not only one created by this helper—is intended to be reused. - Assistant
Every request is wrapped in
runWithAdapter, sorunWithTransactionis normally called with an existing store containing the request’s base adapter. Reusing merely “any store” would therefore skip transactions entirely. The distinction is important: the fix must reuse only an active transaction, not the request-level adapter context. I’ll inspect the store’s recent history and adapter type shape to determine whether transaction state is already represented or needs a private marker. - Assistant
A plain “store exists” check would be incorrect because
runWithAdapterestablishes a non-transactional store around every request. I’ll add an internal transaction-state flag toHookContext: request contexts set it false, transaction contexts true, and nestedrunWithTransactioncalls execute directly in the outer context. This also ensures nested post-transaction hooks remain queued on the outer transaction. First I’ll run a temporary mock reproduction proving the current code opens two transactions even inside the request wrapper. - Assistant
The temporary script is ready, but the pinned
pnpmlauncher attempted an interactive Corepack download, which this environment does not support. I’ll use the already-installed workspace binaries directly (or Corepack’s noninteractive environment switch) to run the reproduction. - Assistant
tsxis not installed, but Vitest is. I’ll place the same one-shot reproduction in a temporary repository file (not an existing or submitted test), run it with Vitest, and remove it after verification. - Assistant
The initial Vitest invocation selected the core workspace but could not resolve the package self-reference because workspace links are incomplete. I’ll inspect the Vitest workspace configuration and available package links, then run the reproduction through the repository’s intended package command/config rather than changing source imports.
- Assistant
I found the package-specific config; I’ll inspect it and rerun from the core package context.
- Assistant
The package config confirms the source-resolution failure is an incomplete workspace installation, not the reproduction itself. I’ll now make the minimal core change: explicitly distinguish request adapter contexts from transaction contexts and short-circuit nested transaction calls only for the latter. Afterward I’ll install/link dependencies noninteractively if needed and rerun the temporary test.
- Assistant
python3is unavailable, so no file changed. I’ll apply the same focused edits with the repository’sedit/replaceutilities. - Assistant
The patch now preserves the ordinary request-level transaction opening while making only nested transaction scopes reentrant. Next I’ll repair workspace links with the pinned package manager in noninteractive mode, format the touched source, and rerun the reproduction.
- Assistant
The installation completed and should have created package-local workspace links. I’ll run Biome on only the source file and then execute the temporary reproduction again.
- Assistant
Workspace linking did not resolve the package’s self-import under this stripped checkout, so I’ll use a temporary Vitest config that aliases only
@better-auth/core/async_hooksto its source file. This does not alter production code and will let the regression harness exercise the real transaction implementation. - Assistant
The regression harness now receives one transaction instead of two, which is exactly the fix; its original assertion intentionally expected the pre-fix count. I’ll update the temporary assertion to the desired behavior and verify it passes. I’ll also inspect the 1.6.11 tag/history to ensure the request-level context distinction remains compatible with the affected release semantics.
- Assistant
The temporary regression now passes with exactly one transaction, while the outer request context still opens that transaction. I’ll remove all temporary files, then run the core typecheck and locate/run existing magic-link and transaction-adjacent tests.
- Assistant
Core typechecking passes. I’ll run the existing magic-link plugin suite and the secondary-storage magic-link unit suite, using their package configurations. If source self-resolution recurs, I’ll distinguish infrastructure failure from code failure and use the repository’s appropriate config/conditions.
- Assistant
Both existing suites are blocked before collection because
@better-auth/coredistribution files are absent in this source-only checkout; this is unrelated to the patch. I’ll build the core package to provide its exported modules, then rerun the suites from their package working directories as their scripts expect. - Assistant
Core build succeeds. The magic-link suite advances further but is now blocked by another absent workspace build (
@better-auth/kysely-adapter) before test collection. Rather than building the entire monorepo, I’ll run the existing core test suite (now that core self-exports exist), check lint on the changed file, and inspect the final diff/status for generated artifacts. - Assistant
All 26 core test files pass (322 tests), and formatting/lint/typecheck are clean. One compatibility refinement is warranted: the ALS getter is exposed for advanced use, so making a new context field required could force advanced callers to supply it. I’ll make the internal marker optional and present only for transaction-created contexts. This preserves existing context construction compatibility while still recognizing active transactions, including contexts shared from older Better Auth instances. Then I’ll rerun typecheck/core tests.
- Assistant
The base-context simplification applied, but the marker type edit did not because the editor utility constrained its visible range; typecheck correctly caught the intermediate mismatch. I’ll apply that one-line change directly and rerun the validations.
- Assistant
The compatibility-adjusted implementation passes core typecheck and all 322 core tests. I’ll perform a final review for whitespace, accidental files, and exact diff scope. I’ll also confirm the built output is ignored and only the intended source file will be submitted.
- Assistant
Final review shows exactly one modified source file with no whitespace errors or temporary artifacts.
Checklist:
- Successfully reproduced the reported error: Yes. A temporary mock adapter harness showed the original nested flow invokes
adapter.transactiontwice; after the patch, its pre-fix assertion (2) failed with an actual count of1, demonstrating the nested transaction was eliminated. - Confirmed the fix resolves the error: Yes. The temporary regression harness passed when asserting one transaction, including an outer non-transactional
runWithAdapterrequest context and nestedrunWithTransactioncalls. - Considered edge cases: Yes. The implementation distinguishes ordinary request adapter contexts from active transaction contexts, so normal calls still open a transaction. Nested calls reuse the active transaction and its pending-hook queue. The marker is optional to remain compatible with existing/advanced ALS contexts and shared older contexts.
- Successfully reproduced the reported error: Yes. A temporary mock adapter harness showed the original nested flow invokes
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.