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
Let me start by exploring the repository structure to understand the codebase.
Assistant
Now I understand the issue. Let me look at the other related files:
Assistant
Now I understand the structure. Let me also check the
DBTransactionAdaptertype:Assistant
Now let me check the
consumeVerificationValueimplementationthat was added in 1.6.11 to understand the deadlock path:Assistant
Now let me look at
consumeOneWithHooks:Assistant
Let me check the factory default for
consumeOne:Assistant
Let me check how the kysely adapter works:
Assistant
Let me check the zenstack adapter:
Assistant
Now I understand the issue clearly. Let me look at the full context and existing tests:
Assistant
Let me look at existing tests in this area:
Assistant
Let me look at the structure of the test for context tests:
Assistant
Let me now look at the structure of the factory.test.ts to understand how tests are setup:
Assistant
Now let me create a reproducer to verify the issue:
Assistant
Now let me write a quick reproduction script first:
Assistant
Let me write a reproduction script:
Assistant
Let me write the test inside the
src/contextdirectory:Assistant
Let me see how other tests resolve this:
Assistant
The existing tests are also broken - they can't resolve
@better-auth/core/async_hooksself-reference. So the tests aren't actually running. This is a known issue - the tests would need a build first. Let me see if there's a way to run tests viathe dist folder:Assistant
Let me run vitest from the root:
Assistant
Let me check what test setup works currently:
Assistant
Let me check whether the pnpm workspace is set up:
Assistant
Let me check the structure more carefully:
Assistant
Good, that test works. The issue is just with the
transaction.tsfile becauseof the self-import. Let me check what's going on:Assistant
I see - the import
@better-auth/core/async_hooksis supposed to be../async_hooks(a relative path within the package). The build withdev-sourceshould resolve this, but it's not resolving. Let me check if there's someworkspace setup that needs to be done:Assistant
Let me check the imports field:
Assistant
The export
./async_hooksexists with adev-sourcefield. The issue is that this is a self-reference (@better-auth/core/async_hooksfrom@better-auth/coreitself), and pnpm doesn't always create the necessary symlinks.Let me check if there's anexisting test that actually uses this pattern:
Assistant
The self-reference doesn't exist in node_modules. Let me see how pnpm creates this self-reference. We need to symlink
@better-auth/coreto itself:Assistant
Let me also remove the symlink and try a different approach. Let me see if other packages use the self-reference pattern successfully:
Assistant
The test infrastructure is broken. Let me try installing dependencies:
Assistant
@better-auth/coreis missing frompackages/core/node_modules/@better-auth/. This is the self-reference that pnpm didn't create. Other packages have it because they're separate packages. The fix would be to add the symlink. Since this is a test infrastructure issue not related to my fix, let me create the symlink manually and verify it works:Assistant
The symlink isn't quite right. The symlink should point to where the
@better-auth/corepackage files are. Let me check how other workspacesdo this:Assistant
The symlink is now correct and the package.json has the
async_hooksexport withdev-source. But it's still failing. Let me check the vitest config morecarefully:Assistant
The test infrastructure is broken for any tests that use self-referencing imports within the
@better-auth/corepackage. Let me check ifpnpm installcreates those symlinks:Assistant
Let me investigate what's happening. Even with the symlink the test fails. Let me check if there's a global setup file that overrides things:
Assistant
The files exist. So the package itself has the source files accessible via the symlink. The issue must be with how vitest is loading the package. Let me check the resolve.conditions being set correctly:
Assistant
The test infrastructure is broken. I'll make the fix and verify it manually with a small reproduction script. Let me first write a standalonereproducer:
Assistant
Confirmed the deadlock. Now let me make the fix to
runWithTransaction:Assistant
Now let me apply the fix:
Assistant
Now let me verify my fix works with the same reproduce script:
Assistant
Let me search the codebase more carefully:
Assistant
Let me check if the factory's
consumeOneis itself wrapped inrunWithTransaction:Assistant
Let me check if
consumeOnetriggersrunWithTransactionanywhere:Assistant
Let me search the zenstack adapter approach more thoroughly:
Assistant
Let me also look at the factory's
consumeOnemore carefully - it's the actual deadlock path:Assistant
Let me check the zenstack adapter's consumeOne implementation pattern:
Assistant
Let me check the Prisma adapter's consumeOne:
Assistant
Now let me look at how to fix the factory's
consumeOnefallback. First, let me check the structure:Assistant
Let me search for any other paths:
Assistant
Now I understand the actual deadlock source. The factory's
consumeOnefallback (used when the adapter has no nativeconsumeOne, like zenstack) callsadapter.transaction(...)directly without checking if we're already inside one. Let me look at this:Assistant
Let me check imports in factory.ts:
Assistant
Now let me update the factory's
consumeOnefallback to reuse the active transaction. First, let me look at the exact lines:Assistant
Let me write the fix for the factory's
consumeOnefallback:Assistant
Now let me apply this patch to factory.ts:
Assistant
Oops, my sed was wrong. Let me reset and do it properly:
Assistant
Now let me replace the consumeOne fallback:
Assistant
Let me write a node script to do the replacement:
Assistant
The file uses 5 tabs and 6 tabs for the indentation. Let me fix the script:
Assistant
Let me look at the structure more carefully. I have 5 tabs for the closing
);. Let me see the lines 1406-1412:Assistant
I see, the line
${T}${T}${T}${T}${T}),is at the same indent as});for the inner function (8 tabs vs 7 tabs). Wait actually}),is 7 tabs (let me count: ^I^I^I^I^I^I^I), that's 7. And the next line is 5 tabs (${T}${T}${T}${T}${T});).Let me adjust the oldLines array - lineindex 46 needs to be 7 tabs, not 6:
Assistant
The expected line is
"\t\t\t\t\t\t\t),"(7 tabs + "),"). But in the file, that line is^I^I^I^I^I^I^I),$which is 7 tabs + "),". So it should match... unless the\tis not being interpreted correctly. Let me check the actual line:Assistant
So line 1408 is
}),with 7 tabs and line 1409 is);with 5 tabs. My oldLines had}),at 7 tabs but);at 5 tabs. But the error says it couldn't find"\t\t\t\t\t\t\t),". That's 7 tabs + "),".Let me see - the actual line in the file:
- line 1408:
}),with 7 tabs
The expected in oldLines array at index 46 is
${T}${T}${T}${T}${T}${T}${T}),which is 7 tabs + "),". Should match.Wait, the index 46 means line 46 (0-indexed) in the array. Let me count:
- 0:
} else { - 1:
// TODO...
- line 1408:
Assistant
Let me check why the replacement doesn't match:
Assistant
So the actual line is
"\t\t\t\t\t\t\t}),"(7 tabs +}),), not),. Let me fix the array:Assistant
Let me check if there are any other characters:
Assistant
Aha! Line 1362 is
} else {with 4 tabs (not 5). And line 1363 is// TODO...with 4 tabs too. Let me checkmore lines:Assistant
I see - the indentation is different than I thought. Let me redo with correct indentation:
Assistant
All lines are found individually. But the joined oldSection is not found. This means there's some issue with line breaks or whitespace. Let me look more carefully:
Assistant
There are MULTIPLE
} else {lines with 4 tabs. Let me find the correct one:Assistant
Now let me write the proper replacement:
Assistant
Strange - the start idx is -1. Let me check more carefully. Maybe there are special characters:
Assistant
Let me re-count the actual indentation:
Assistant
Now let me look at the rest of the structure carefully:
Assistant
Now I have the exact structure. Let me write the replacement:
Assistant
Let me verify the result:
Assistant
Let me check the indentation of the inner content:
Assistant
I see - the replacement is missing 2 tabs on the inner content. Let me fix it:
Assistant
Now let me write the replacement with correct indentation matching the original:
Assistant
The indentation is correct. Let me view the result:
Assistant
I see - the indentation is wrong in the inner content. Let me fix it:
Assistant
The indentation now looks correct. Let me verify the format:
Assistant
Let me fix the type error:
Assistant
The error is at
getCurrentAdapteritself, because it expectsDBTransactionAdapter(without generic Options parameter), but I'm passingDBTransactionAdapter<Options>. Let me look at the signature:Assistant
Type-check passes. Let me check the rest of the packages that import from core:
Assistant
Let me build the core first:
Assistant
The build succeeded (warnings about unresolved imports are pre-existing). Let me verify by checking the dist file:
Assistant
The transaction.mjs is built correctly. Now let me verify the factory fallback:
Assistant
Both fixes are in place. Now let me write a comprehensive test to verify both fixes work:
Assistant
Test 1 passes. Test 2 is just my faulty test setup - let me fix it:
Assistant
All tests pass. Let me also verify that without my fix, the same tests would fail (just to make sure my reproducer is valid):
Assistant
Test 1 confirms the deadlock bug without my fix. Let me restore my fix:
Assistant
All tests pass with my fix. Now let me also run a more comprehensive end-to-end test simulating the actual call chain from
consumeVerificationValue:Assistant
Let me also test the factory fallback path explicitly:
Assistant
The factory expects a function that returns the adapter. Let me fix the test:
Assistant
The customAdapter doesn't have consumeOne. The factory should add it. But looking at the factory code, it requires a certain shape. Let me checkthe schema:
Assistant
The factory expects
customAdapterto be a function that takes options and returns the adaptermethods. So I need to refactor my test adapter to be a factory function:Assistant
The end-to-end test with the factory fallback passes. Let me also verify that the test FAILS without my fix:
Assistant
Let me restore my fixes:
Assistant
Let me view the final state of my changes:
Assistant
Let me run existing tests to make sure nothing is broken:
Assistant
All existing core tests pass. Now let me check the better-auth package which depends on these changes:
Assistant
Let me also run the better-auth tests for the affected files:
Assistant
The test fails because of a missing build of
@better-auth/kysely-adapter. This is unrelated to my changes - it's a build issue. Let me try building the kysely-adapter first:Assistant
All 51 tests in
internal-adapter.test.tspass! Let me run a wider set of tests to ensure nothing is broken:Assistant
The 2 failures are unrelated to my changes (one needs Postgres connection, one needs mongo-adapter). Let me also test the magic-link tests if any:
Assistant
All 18 magic-link tests pass! Let me also run the unit tests for magic-link:
Assistant
All 6 tests pass. Let me run more tests:
Assistant
Only 1 test fails out of 1158 - it's a Postgres connection issue. Let me also run a wider set of better-auth tests to make sure my changes don't break anything:
Assistant
All 373 API tests pass. Let me also run the db test that I want to verify:
Assistant
All 51 tests pass. Let me also verify my changes are compatible with the existing transaction-related code:
Assistant
All organization plugin tests pass. Let me also verify the type checking works in the better-auth package:
Assistant
Let me clean up my test files since I shouldn't add tests per instructions:
Assistant
Let me verify that the import is correct (no circular imports):
Assistant
Let me do a final verification:
Assistant
The verification is too strict - it's counting tx across test sections. Let me fix it:
Assistant
All verifications pass. Let me clean up:
Assistant
Let me do a final comprehensive check by running the full core test suite:
Assistant
All 322 core tests pass! Let me now look at the final state of my changes:
Assistant
The changes are clean and complete. Let me do a final summary of what was changed and why:
Summary
The issue described a deadlock that occurs when using
magicLinkverify with a database adapter whosetransactionimplementation acquires a real connection from a connection pool (like Kysely, or zenstack withpg). This is especially problematic when the pool has only one connection (e.g., Cloudflare Hyperdrive-fronted with ).Assistant
Both packages pass TypeScript checks. Now let me address the checklist:
Assistant
Checklist
Going through the checklist:
-
If an error was reported in the issue description, I have successfully reproduced it. ✅
- I created a Node.js script that reproduced the deadlock scenario: a single-connection-pool adapter that hung forever when nested transactions were attempted. The script confirmed the deadlock happens.
-
If an error was reported in the issue description, I have confirmed that my fix resolves the error. ✅
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.