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 can see the issue. Let me explore more context to understand the issue thoroughly.
Assistant
Let me look for all callers of
consumeVerificationValue:Assistant
Now let me look at the actual issue - the call chain from magic link verify:
Assistant
Now let me understand the issue more. Let me look at the
runWithTransactionfunction and see how it should be fixed:Assistant
Now I understand the structure. Let me trace the issue clearly:
magicLinkVerifycallsconsumeVerificationValueconsumeVerificationValueusesrunWithTransactionto open a new transaction- Inside the transaction, it calls
consumeOneWithHooks→txAdapter.consumeOne consumeOne(provided by the factory fallback) wrapsfindMany + deleteManyin its ownadapter.transaction(...)call- This nested
adapter.transactioncall needs a second connection, but the pool is limited to 1, so it deadlocks.
Let me see the consumeOne fallback:
Assistant
Now I have a clear understanding. The issue is twofold:
- The fallback for
consumeOneinfactory.tsopens its ownadapter.transaction - The
runWithTransactiondoes not check if there's already an active transaction
The fix is to make
runWithTransactionreentrant - it should checkadapterAsyncStorage.getStore()and reuse the existing transaction if there is one, similar to howgetCurrentAdapterworks.Let me look at the issue more carefully:
- The fallback for
Assistant
Now let me understand the fix needed. The fix should be to make
runWithTransactionreuse an existing active transaction if one is present in the AsyncLocalStorage store. Let me look at how the queueAfterTransactionHook works:Assistant
Now let me check the test for transaction:
Assistant
Let me also look at the consumeOneWithHooks to understand the call chain:
Assistant
Now I have a clear picture of the issue. Let me implement the fix. The fix is to make
runWithTransactionreentrant - when called from within an active transaction context, it should reuse the existing transaction instead of opening a new one.Assistant
Now I'll implement the fix. The key change is in
runWithTransaction: when there's an existing transaction context (an adapter is already in the AsyncLocalStorage store), we should reuse the active adapter and executefnwithin that context, rather than opening a new transaction.Assistant
Let me try a different approach with replace:
Assistant
Let me use a different approach using
cat > file << EOF:Assistant
The fix is in place. Now let me think through edge cases and look at the consumeOne fallback in factory.ts. The factory fallback opens its own
adapter.transactionwhich means even thoughrunWithTransactionis now reentrant, the factory'sconsumeOnefallback will still try to open a new transaction. Let me look at the factory's fallback code again to see if it also needs to be made reentrant:Assistant
Let me understand the factory wrapper better:
Assistant
Let me re-check the call chain - the issue says consumeOne triggers another
runWithTransaction:Assistant
Let me look at the imports in factory.ts:
Assistant
Let me check for circular import concerns:
Assistant
Let me look at the kysely adapter to understand its transaction support:
Assistant
Let me check the current version and see when this fallback was added:
Assistant
OK, so the
consumeOnefallback was added in 0cbddb8fa (renamed from claimOne), and theincrementOnefallback was added in baeaa00bc. Both useadapter.transactiondirectly.Let me also look at the actual changes forconsumeOne:
Assistant
Let me check the package.json for the exports:
Assistant
Now let me also fix the factory's
consumeOneandincrementOnefallbacks to be reentrant:Assistant
Let me implement the fix to the factory's
consumeOneandincrementOnefallbacks. First, let me check howrunWithTransactionandgetCurrentAdapterwould be imported:Assistant
Let me check if kysely's
consumeOneis reentrant:Assistant
Let me trace through
consumeOneWithHooksandconsumeOnemore carefully:Assistant
Now I'll fix the factory's
consumeOneandincrementOnefallbacks to also be reentrant. Let me first understand the impact:Assistant
Now let me implement the fix to the factory's
consumeOneandincrementOnefallbacks:Assistant
Let me add the import for
getCurrentAdapterandrunWithTransaction:Assistant
Now let me update the
consumeOneandincrementOnefallbacks:Assistant
Good. Now let me also update the FIXME comments:
Assistant
Let me update the FIXME comments to reflect the new behavior:
Assistant
Let me verify the structure around the changes:
Assistant
Now let me verify the changes compile and run the existing tests:
Assistant
Let me check the types:
Assistant
Let me make
runWithTransactionandgetCurrentAdaptergeneric:Assistant
Let me make
runWithTransactionandgetCurrentAdaptergeneric:Assistant
Let me fix the type parameter ordering:
Assistant
The error is about the type parameter ordering. Let me look at line 49 and 90:
Line 49 is
runWithAdapterwhich has<Options extends BetterAuthOptions = BetterAuthOptions, R,>. Line 90 isrunWithTransactionwhich has<Options extends BetterAuthOptions = BetterAuthOptions, R,>.The error is "Required type parameters may not follow optional type parameters". So
R(required) cannot followOptions = BetterAuthOptions(optional with default).Let me restructure. I can either:
- Put
Rfirst, thenOptions - Remove the default for
Options
Let me put
Rfirst:- Put
Assistant
Now let me verify the better-auth package:
Assistant
Let me check if the better-auth package compiles by checking dependencies:
Assistant
These errors are pre-existing and not related to my changes. Let me check by reverting and verifying:
Assistant
Good - these errors are pre-existing. Let me restore my changes:
Assistant
Core compiles. Let me verify the kysely-adapter and other adapter packages still compile:
Assistant
Good - the kysely adapter has pre-existing errors, not related to my changes. Let me now write a quick test to verify my fix works:
Assistant
Let me write a quick test to verify the reentrancy of
runWithTransaction:Assistant
Let me change the import to a relative path:
Assistant
The setup uses pnpm workspaces. Let me check if I can build the core package orrun tests:
Assistant
Build is working. Let me run the test now:
Assistant
The first 2 tests pass! The 3rd test has a bug in my test - the outer
runWithTransactiondoesn't return anything. Let me fix:Assistant
All 3 tests pass. Now let me remove the test file (since the rules say not to add new tests):
Assistant
Now let me run existing tests in core to make sure my changes don't break anything:
Assistant
All 322 tests pass. Now let me also test the better-auth package:
Assistant
Need to build the kysely-adapter package:
Assistant
Let me build the mongo adapter and try again:
Assistant
Let me check the timeout test to see if it's related to my changes:
Assistant
This test uses MongoDB which probably needs a running MongoDB. Let me check if it's a pre-existing failure:
Assistant
Good - the test failure is pre-existing and not related to my changes. Let me run the internal-adapter tests:
Assistant
All 51 internal-adapter tests pass. Let me run the magic link tests:
Assistant
All magic link tests pass. Now let me also run the tests for the increment-one:
Assistant
All passing. Let me check the factory tests:
Assistant
Tests pass. Now let me write a test to simulate the actual scenario from the issue - using a real adapter with limited connection pool:
Assistant
Let me fix the test - I need to add
consumeOneto the trx object:Assistant
The fix works. Let me now verify that without the fix, this test would fail. Let me temporarily revert the fix and test:
Assistant
Without my fix, the test fails with "DEADLOCK: cannot acquire second connection from size-1 pool" - this confirms my fix resolves the issue. Now let me restore my changes:
Assistant
Let me run the repro test again to confirm the fix is back:
Assistant
Let me remove the repro test file now since we can't add new tests to the repository:
Assistant
Let me look at the outer factory consumeOne flow more carefully:
Assistant
Let me also run the factory tests again to make sure they still pass:
Assistant
All 29 tests pass. Let me also check that the better-auth internal adapter tests still work:
Assistant
Let me also run the magic-link tests to ensure they pass:
Assistant
All 18 magic link tests pass. Let me also run the email-otp tests:
Assistant
All 81 email-otp tests pass. Let me also run the captcha plugin tests which use consumeVerificationValue:
Assistant
All tests pass. Let me also check the rate-limit tests since they use consumeVerificationValue:
Assistant
All 25 rate-limiter tests pass. Let me also run the two-factor tests:
Assistant
All 72 two-factor tests pass. Let me run more plugin tests that use the consume pattern:
Assistant
All 127 tests pass. Let me also run tests on the api-key, sso, organization plugins:
Assistant
Let me see which tests are failing to make sure they're not related to my changes:
Assistant
These are all build-related issues with missing packages. Let me build the better-auth package andtry again:
Assistant
The test failure is because of a postgres connection issue (ECONNREFUSED), not related to my changes. Let mealso run the SSO tests:
Assistant
All 388 SSO tests pass. Let me run the organization tests:
Assistant
All 229 organization tests pass. Let me also run the test for the device authorization plugin:
Assistant
All 42 device authorization tests pass. Let me check the api-key:
Assistant
The api-key test failure is due to postgres connection refused, not related to my changes. Let me look at the final state of my changes:
Assistant
Let me check the final version of the transaction.ts:
Assistant
Let me check the factory.ts:
Assistant
Let me create a temporary test file to verify the fix again, then remove it:
Assistant
Excellent! The fix works as expected. Let me also create a changeset for the change:
Assistant
Let me check how
runWithAdapteris used:Assistant
I realize there's a subtle issue. Let me re-think:
The issue is that
runWithAdapteralso sets the ALS store with the base adapter. If my simple fix reuses that, it would lose atomicity whenrunWithTransactionis called insiderunWithAdapter.Let me update the fix to only reuse when there's an actual transaction context:
Assistant
All tests pass. Let me re-test the magic-link verify scenario with the updated fix:
Assistant
Let me see the full error:
Assistant
Let me check if
runWithAdapteris actually setting the flag:Assistant
Let me check what's actually compiled. First, let me rebuild:
Assistant
Let me run just the second test:
Assistant
The test passes now. The issue was with my earlier test that had
vi.fnmock state persistence between tests. The fix is working correctly. Let me also verify the original deadlock fix still works:Assistant
Both tests pass. Now let me also verify that the fix is in place by looking at the diff:
Assistant
Let me run all the relevant tests once more:
Assistant
All 235 tests pass. Let me also run the tests for the api-key, sso, organization, two-factor plugins:
Assistant
All 816 tests pass. Let me also run the core tests to ensure nothing is broken:
Assistant
All 322 core tests pass. Now let me also test a few other areas:
Assistant
All 222 tests pass. Let me also check tests related to update-user, password, two-factor verify:
Assistant
All tests pass. Let me also check for the
consumeVerificationValuetests specifically:Assistant
All 14 consumeVerificationValue tests pass. Now let me look at the final state of the code:
Assistant
Let me also look at the final state of the transaction.tsfile to make sure it's clean:
Assistant
Let me check all places that use
runWithTransactionto make sure my fix is compatible:Assistant
Let me look at the organization adapter:
Assistant
Let me check the sign-up route:
Assistant
Let me verify the complete diff:
Assistant
Let me run a final sanity check on all the relevant tests:
Assistant
All 727 tests pass. Let me also verify by running a comprehensive test:
Assistant
The hooks order is FIFO (queued first, executed first). Let me verify this is correct:
Assistant
All 5 comprehensive tests pass. The fix is complete and correct.
Let me also check the existing tests to make sure the fix doesn't break anything:
Assistant
Now let me also re-examine the changeset:
Assistant
Let me do a final check to make sure I haven't introduced any new test files:
Assistant
No new test files. Let me also verify that I haven't introduced any changes outside the relevant areas:
Assistant
Only the relevant files are changed.
Let me also verify the changeset one more time:
Assistant
Let me look at the final state of all the changes:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.