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 nested call behavior with the smallest existing test harness before changing it. Afterward I’ll run the focused package tests and relevant type/lint checks.
- Assistant
rgis unavailable, so I’ll usegrep/find. I’m also checking repository-specific contributor guidance before editing. - Assistant
The implementation is in
packages/core/src/context/transaction.ts. Next I’ll inspect its adapter identity semantics and nearby core tests/package scripts, because blindly reusing any ALS store could be wrong if nested calls involve a different base adapter. - Assistant
The ALS store currently does not distinguish
runWithAdapterfrom a real transaction. The issue’s requested behavior says reuse when an adapter/transaction is active, mirroringgetCurrentAdapter, so the intended implementation is to callfn()whenever a store exists. This also preserves the outer store’spendingHooks, ensuring nested “after transaction” hooks execute only after the outermost transaction. I’ll confirm adapter types and global reset facilities, then create a temporary reproduction script (not a repository test, per the environment restriction). - Assistant
I’ll reproduce the defect by nesting
runWithTransactioncalls against a mock interactive adapter and asserting only one transaction acquisition. The mock won’t actually hang; transaction-call count2is the deterministic proxy for requesting the second pooled connection. The temporary script will be removed before submission. - Assistant
Corepack attempted an interactive package-manager download, which this environment does not support. I’ll invoke the already-installed workspace binaries directly; if
tsxis absent, Vitest can execute a temporary test outside the repository without modifying tracked tests. - Assistant
I’ll place the temporary reproduction under
packages/coreonly for execution, then delete it immediately. It will never be part of the submitted diff. - Assistant
The first harness attempt was blocked by an environment/module-resolution issue (
@better-auth/core/async_hooksis not linked in the partial install), not by the assertion. I’ll inspect Vitest workspace aliases and package symlinks to run the focused project correctly rather than changing source imports. - Assistant
The package’s own config may define the missing self-reference alias. I’ll inspect it and rerun with that config if appropriate.
- Assistant
The workspace install is missing the
@better-auth/coreself-link. I’ll temporarily create that normal workspace symlink, rerun the reproduction, and remove the symlink afterward. This changes no tracked files. - Assistant
The root scope directory itself is absent (the earlier listing came from the package-local scope), so I’ll create/remove the temporary scope directory explicitly and rerun.
- Assistant
Vitest is not applying the root
dev-sourceexport condition to this self-reference in the partial install. I’ll use a temporary Vitest config with an explicit alias to the source async-hooks entry. This isolates the harness problem without touching production code. - Assistant
The reproduction now fails exactly as reported: the nested call invokes
adapter.transactiontwice. I’ll makerunWithTransactioncheck the active ALS store before allocating pending hooks or opening a transaction. Returningfn()directly keeps the outer transaction adapter and hook queue active through async-context propagation. - Assistant
The line-range edit replaced the
.thenwrapper rather than inserting inside it, producing invalid syntax and a duplicate declaration. I’ll correct that block immediately and review the exact diff again. - Assistant
The corrected diff is now the intended three-line guard. I’ll rerun an expanded temporary regression harness that verifies: one transaction acquisition, nested CRUD sees the outer transaction adapter, nested hooks stay queued until the outer transaction completes, and nested errors propagate without opening another transaction.
- Assistant
The post-fix harness passes both transaction reuse and hook/error edge cases. I’ll now run the complete existing
@better-auth/coretest suite using the same temporary resolution alias required by this partial workspace install, followed by the core package typecheck and a targeted Biome check. - Assistant
Core typechecking and formatting pass. The suite ran 313 tests successfully, while two test files failed to import because the partial workspace also lacks the core self-reference for
@better-auth/core/instrumentation; there were no assertion failures. I’ll rerun those two files with both explicit source aliases, then locate and run the existing magic-link tests since that is the affected user flow. - Assistant
All previously blocked core tests pass with correct resolution (322/322 total across the two runs). I’ll run the existing magic-link plugin test file now; if the partial install has further workspace-link gaps, I’ll distinguish infrastructure import failures from test failures as before.
- Assistant
The magic-link suite is blocked before collection by another missing core workspace self-link. Rather than enumerate many core subpath aliases, I’ll inspect package-local workspace links and temporarily add the expected
packages/better-auth/node_modules/@better-auth/coresymlink, which should let export conditions resolve naturally from the consuming package. - Assistant
The expected symlink already exists; the issue is that this Vitest version is not honoring the repository’s
ssr.resolve.conditionsplacement. I’ll rerun with a temporary config settingresolve.conditions: ["dev-source"], preserving the package’s normal project options. - Assistant
The condition override still fails, suggesting a broken or inaccessible package link rather than source code. I’ll verify Node’s own resolution from the consuming package and inspect the symlink target/package export directly. This is only to accurately characterize why the unrelated integration suite cannot start.
- Assistant
Node resolves the package correctly from
packages/better-auth; Vitest resolves dependencies from the workspace root, where the link is missing. I’ll combine a temporary root link with the correcteddev-sourcecondition and rerun the magic-link suite, then clean both up. - Assistant
The magic-link suite remains uncollectable due Vitest’s workspace package-resolution behavior in this environment, even though Node resolves the same export and the focused transaction regression executes successfully. The affected core package has passed all 322 existing tests, typecheck, and Biome. I’ll perform a final diff/status audit to ensure no temporary files or links remain and review the exact implementation once more.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.