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 start by exploring the repository structure and finding the relevant files mentioned in the issue.
Assistant
Now let me find
consumeVerificationValueto understand the call chain.Assistant
Now let me look at
consumeOneWithHooksto see how it usesrunWithTransaction.Assistant
Let me look at the
consumeOne/deleteWithHooksand how CRUD operations userunWithTransaction.Assistant
Let me look at where
consumeOneis implemented in adapters.Assistant
So the kysely
consumeOnefor MySQL callsdb.transaction().execute(...)when not in a transaction (inTransactionfalse). Let me look at howinTransactionis determined. Let me look at how the adapter'stransactionmethod works in kysely.Assistant
Now I understand the structure. Let me reproduce the issue with a test script using a mock adapter whose
transactionacquires a connection from a pool of size 1.Assistant
Let me write a reproduction script to confirm the deadlock with the current code.
Assistant
No dist. Let me build the core package or just write a test that imports the TypeScript source via tsx/esbuild. Let me check if there's a way to run TS. Let me check the package.json scripts and whether tsx is available.
Assistant
Let me write a vitest test that imports from the source directly. Let me check how existing core tests are set up.
Assistant
Let me create a temporary test for
runWithTransactionreentrancy in the core package.Assistant
The
@better-auth/core/async_hooksimport isn't resolvable. Let me check how the package resolves these internal imports in tests.Assistant
The
dev-sourcecondition resolves@better-auth/core/async_hooksto./src/async_hooks/index.ts. The root vitest config setsssr.resolve.conditions: ["dev-source"]. But the core package's own vitest.config doesn't set this. Let me run the test from the root with the root config, which should use thedev-sourcecondition.Wait, the root config has
projects: ["./packages/*", ...], so the core project config is used. But the core's vitest.config doesn't set thedev-sourcecondition. Hmm. Let me check how other core tests resolve@better-auth/core/...imports. Let me look at the request-state test which is in context.Assistant
The existing tests in core use relative imports (./request-state), not the
@better-auth/core/...package imports. The transaction.ts imports@better-auth/core/async_hookswhich is a self-package import. That needs thedev-sourcecondition.Let me check how the core package resolves self-imports. Maybe there's a tsconfig paths setting or the vitest config in core needs the condition. Let me check if there's an existing test that imports something that triggers the
@better-auth/core/async_hooksresolution. The request-state.test imports./request-statewhich probably imports@better-auth/core/async_hookstoo.Assistant
So even the existing request-state test fails when run standalone because the
dev-sourcecondition isn't applied. Let me check how CI runs these tests and whether there's an alias or paths mapping.Assistant
The
customConditions: ["dev-source"]is in tsconfig but vitest needsresolve.conditions. The root vitest config hasssr.resolve.conditions: ["dev-source"]. But the test failed because it's running in the core project (which has its own vitest.config without the condition), and the test environment might benodenotssr.Actually, vitest's
ssr.resolve.conditionsapplies to SSR environment. By default vitest uses node environment. Let me check if there's a way the existing tests run. Let me check how tests are run in CI - look at package.json test script.Assistant
Let me check the better-auth package's vitest config which likely sets the dev-source condition. The internal-adapter.test.ts runs
consumeVerificationValuewhich usesrunWithTransaction.Assistant
The better-auth vitest config doesn't set dev-source either, yet the internal-adapter.test must pass. Let me run the existing consumeVerificationValue test to see if it resolves correctly.
Assistant
The test fails standalone because the
dev-sourcecondition isn't applied. Let me check how@better-auth/coreis linked and whether there's a node_modules symlink.Assistant
No
node_modules/@better-auth/at root. The packages use pnpm workspace symlinks. Let me check the better-auth node_modules for @better-auth/core.Assistant
So
@better-auth/coreis symlinked. The exports map usesdev-sourcecondition. Let me check if vitest appliesssr.resolve.conditions. Let me try creating a config override withresolve.conditions.Assistant
The core package's own
node_modulesdoesn't have@better-auth/coreself-symlink. The@better-auth/core/async_hooksself-import requires self-referencing. Let me check core's node_modules.Assistant
The core package doesn't have a self-link. Node's self-referencing uses the package.json
name/exports. Let me check turbo.json to see if thetesttask depends on a build step (generating dist).Assistant
The
testtask depends onbuild, so tests run against the builtdist(thedefaultexport condition). Self-referencing resolves to dist. Let me build the core package first, then I can test against dist.Assistant
The build timed out. Let me check the node version and try a faster approach to test the actual source.
Assistant
Node v24, tsx available. Let me try running the actual source with tsx. First let me check
getAsyncLocalStorageand__getBetterAuthGlobalto understand dependencies.Assistant
The
import.meta.env.BETTER_AUTH_VERSIONis replaced at build time. Tests run against built dist. Let me try building core directly with a longer timeout and see output.Assistant
I can create a vitest config that aliases the self-reference
@better-auth/core/async_hooksto the source file, avoiding the need to build. Let me do that.Assistant
I've reproduced the deadlock with the actual source code. Now let me look at where
runWithAdapteris used to understand an important edge case (what ifrunWithTransactionis called inside arunWithAdaptercontext).Assistant
runWithAdapteris used at the request-handler level (base.ts:89) with the plain adapter. This is a critical edge case: whenrunWithTransactionis called inside arunWithAdaptercontext (plain adapter), it must STILL open a real transaction. So I need to distinguish a transaction context from a plain adapter context. Let me trace the actual magic-link verify path to understand the nesting.Assistant
Let me check the adapter factory's default
consumeOneimplementation (the fallback that may wrap in a transaction).Assistant
Found it. The
consumeOnefallback in the factory callsadapter.transactiondirectly. Let me check git history for the 1.6.11 change to understand the exact nesting.Assistant
Let me look at the
#9993commit "make single-use credentials, counters, and replay markers atomic" — likely the 1.6.11 change.Assistant
This is the 1.6.11 change (#9993). Let me look at how it changed
consumeVerificationValueand the transaction usage.Assistant
In #9993, the
consumeOne/incrementOnefallbacks useadapter.transaction(...). Let me check whatadapterrefers to in that closure (the outer factory adapter vs the trx).Assistant
Let me check
createAsIsTransactionto understand the fallback transaction behavior.Assistant
createAsIsTransactionjust reuses the same adapter. Let me find ALLrunWithTransactioncallers across the codebase to understand every nesting opportunity.Assistant
Let me check the #9993 diff for
consumeVerificationValue'srunWithTransactionusage.Assistant
Let me check the #9572 diff (the magic-link atomic consume) for
consumeVerificationValue'srunWithTransactionusage.Assistant
Hmm, #9572 didn't add
runWithTransactionto consumeVerificationValue in internal-adapter.ts. Let me look at the actual diff of #9572 fully for internal-adapter.ts.Assistant
Let me find which commit added
runWithTransactiontoconsumeVerificationValue.Assistant
consumeVerificationValuewithrunWithTransactionwas introduced in #9560 (the 1.6.11 atomic race fix). Now let me look at the existingconsumeVerificationValuetests to see what adapter they use and whether they'd catch the deadlock.Assistant
The existing tests use
node:sqlitein-memory (no pool deadlock). Let me check whethercreateWithHooks/updateWithHooksor other hook helpers callrunWithTransaction, which could create nesting.Assistant
runWithTransactionis only called increateOAuthUserandconsumeVerificationValue— neither nested in the magic-link verify path. So the actual nestedadapter.transactionfor non-reentrant custom adapters comes from the factory'sconsumeOne/incrementOnefallback. Let me verify by finding the sqlite adapter and checking if it implements nativeconsumeOne.Assistant
Let me find how
DatabaseSyncis turned into an adapter (whereconsumeOnenative impl lives for sqlite).Assistant
better-auth's default sqlite adapter uses the kysely adapter (native
consumeOnevia DELETE...RETURNING), so existing tests don't exercise the factory fallback. Let me check the current repo version/tag to confirm we're at/after 1.6.11.Assistant
Current version is 1.6.18. Now let me check which adapters implement native
consumeOne(vs. falling back to the nested-transaction factory path).Assistant
Most first-party adapters (kysely, memory, mongo, prisma, drizzle) have native
consumeOne. The factory fallback (nestedadapter.transaction) is hit by custom adapters like@zenstackhq/better-auththat don't implementconsumeOne. That's the actual magic-link deadlock. Let me look at theincrementOnefallback too.Assistant
Let me check the import structure to avoid circular dependencies when the factory imports from context/transaction.
Assistant
transaction.tsonly type-imports from../db/adapter, so importingcontext/transactionintofactory.tsat runtime won't create a circular dependency. Let me check the bottom of the db/adapter index exports.Assistant
I now have a clear understanding. The issue asks for
runWithTransactionreentrancy (Fix 1), and the actual magic-link deadlock for non-reentrant custom adapters without nativeconsumeOneis the factory's fallback nestingadapter.transaction(Fix 2). Both should mirrorgetCurrentAdapter. Let me check if any existing tests exercise nestedrunWithTransaction(savepoint semantics) before implementing.Assistant
Only my repro test directly uses
runWithTransaction. Let me check the prisma-adapter test's "nested transaction" reference.Assistant
The prisma test verifies native
consumeOnedoesn't nest. Let me check if kysely/drizzle have similar tests, and whether any test exercises the factory fallback (adapter without native consumeOne).Assistant
Let me check the
createTestAdapterhelper and itstransactionconfig to understand how these fallback tests resolve the transaction.Assistant
The factory fallback tests call
consumeOneoutside any transaction (no ALS context), sogetActiveTransactionAdapter()returns null and they keep usingadapter.transaction(createAsIs) — no behavior change. Now I'll implement the fixes. Let me start withtransaction.ts.Assistant
Now let me edit the
HookContexttype to add theisTransactionflag:Assistant
No python3. Let me use the
editcommand. Let me open the file first.Assistant
Now let me make the edits. First, the
HookContexttype:Assistant
Now let me add the
getActiveTransactionAdapterhelper aftergetCurrentAdapter, and updaterunWithTransaction:Assistant
Now let me update
runWithTransactionto reuse the active transaction:Assistant
The edit left duplicate trailing lines (161-172). Let me view and remove them.
Assistant
I need to remove the duplicate lines 161-172:
Assistant
The file looks clean now. Let me verify the full file:
Assistant
Now let me export
getActiveTransactionAdapterfromcontext/index.ts:Assistant
The replace operates on the currently open file. Let me open the index.ts and edit it.
Assistant
Now let me update
factory.ts. First let me check theDBTransactionAdaptertype to handle generics correctly.Assistant
DBTransactionAdapter<Options>methods don't referenceOptions, so the default-typed adapter is structurally assignable. Now let me update the factory. Let me view the exact consumeOne fallback lines.Assistant
Let me get the exact line numbers for the consumeOne fallback block.
Assistant
Now let me open the factory file and edit the consumeOne fallback:
Assistant
The indentation is off by one tab (my replacement used 3-tab base, but the original used 4-tab). Let me verify and fix by adding one tab to the affected lines.
Assistant
Confirmed: my block is uniformly 1 tab short. Let me add one tab to lines 1361-1425.
Assistant
Now let me verify the full consumeOne block looks correct:
Assistant
There's a double blank line. Let me check and fix:
Assistant
Good, only one blank line. Now let me update the
incrementOnefallback. Let me find its current line numbers.Assistant
Same indentation issue. Let me add one tab to lines 1515-1591:
Assistant
Now let me add the import for
getActiveTransactionAdapterin factory.ts. Let me check the import section:Assistant
Let me add the import after
getAuthTables:Assistant
The replace command says text not found in displayed lines but found at line 10. I need to navigate there. Let me use the edit command on the file directly with the line range. Line 10 is
import { getAuthTables } from "../get-tables";. Let me edit line 10.Assistant
Let me verify the incrementOne block boundary for blank lines:
Assistant
Now let me run my reproduction test to confirm the deadlock (Fix 1) is fixed:
Assistant
Fix 1 is confirmed. Now let me write a reproduction for Fix 2 (factory
consumeOnefallback nesting with a non-reentrant single-connection adapter). Let me create a test using the factory directly.Assistant
Fix 2 confirmed. Let me verify the test is meaningful by temporarily reverting only the factory change (keeping Fix 1) to confirm it deadlocks without Fix 2:
Assistant
Confirmed: without Fix 2 the test deadlocks; with it, it passes. Let me verify the factory.ts was restored correctly after stash pop:
Assistant
Both fixes are in place and validated. Now let me remove my temporary test files and run the existing test suites to ensure no regressions.
Assistant
Temp tests removed. Now let me run existing tests. Since standalone runs need the
dev-sourcecondition (self-references), let me run the core adapter/context tests with the alias config that resolves self-references to source.Assistant
Existing core tests pass. Now I need to run the better-auth tests (consumeVerificationValue, magic-link). These need core built. Let me check if core dist exists, and try building with a longer timeout.
Assistant
The build (with dts) is too slow in this environment. Let me check if dist was partially created and try building without dts.
Assistant
Core dist now built (reflecting my changes, without the slow dts step). Now let me run the better-auth internal-adapter
consumeVerificationValuetests and the magic-link tests:Assistant
The better-auth test needs
@better-auth/kysely-adapterbuilt (dist). Let me build kysely-adapter (and memory-adapter) without the slow dts step.Assistant
The kysely-adapter build timed out at 200s. Hmm. The kysely-adapter might have its own slow config. Let me check its tsdown config and try directly with a longer timeout. Actually, maybe the build is slow because of dependencies. Let me try building kysely-adapter directly with tsdown and --dts false with more time.
Actually, let me reconsider. The earlier core build (no dts) took 108ms. The kysely build timing out at 200s is odd. Maybe
pnpm exec tsdownis doing something else. Let me run tsdown directly in the kysely-adapter dir.Assistant
kysely-adapter built. Let me check the internal-adapter.test imports and run the consumeVerificationValue test again:
Assistant
Need memory-adapter built too. Let me build it directly with tsdown:
Assistant
Let me build all workspace packages with
--dts falsein a loop (fast, avoids pnpm overhead):Assistant
All packages built. Now let me run the consumeVerificationValue tests:
Assistant
consumeVerificationValue tests pass. Let me run the full internal-adapter test suite and the magic-link tests:
Assistant
All 51 internal-adapter tests pass. Now let me run the magic-link tests:
Assistant
Magic-link tests pass. Let me run tests that exercise
runWithTransactionpaths (sign-up, organization) and the with-hooks/db tests to check for regressions:Assistant
Let me see the actual failure detail:
Assistant
The db.test.ts failures are environment issues (Postgres
ECONNREFUSED 5432, mongo-adapter not built) — unrelated to my change. Let me build mongo-adapter and verify these are pre-existing by checking the test setup:Assistant
The db.test.ts
postgrestest needs a running Postgres (ECONNREFUSED 5432) — environment, not my change. Let me check docker-compose and try starting Postgres, then re-run db.test.ts:Assistant
No docker available — the postgres/mongo tests can't run here (environmental, not my change). Let me re-run db.test.ts (mongo now built) to confirm only the postgres-connection test fails:
Assistant
Two failures. The postgres one is environmental. Let me check the "coerce string where values" test — it timed out. Let me inspect it:
Assistant
Both db.test.ts failures are environmental (no postgres/mongodb via docker). Let me confirm they're pre-existing by stashing my changes and re-running db.test.ts:
Assistant
Confirmed: the same 2 failures occur on the original code — they're pre-existing environmental issues (no postgres/mongodb). Now let me rebuild core dist with my changes restored:
Assistant
Core dist rebuilt with my changes. Now let me check whether organization has nested
runWithTransactioncalls (the main regression risk for Fix 1):Assistant
Let me find and run the organization tests (which use
runWithTransaction):Assistant
The output got cut off (showing project configs). Let me run with a tail that captures the final results.
Assistant
Organization crud-invites tests pass. Let me run the team and organization tests too:
Assistant
Organization tests pass (139 passed). No regressions. Let me run the full core test suite to confirm no regressions there:
Assistant
All 322 core tests pass. Now let me run the adapter tests (prisma has the "no nested transaction" test; memory has native consumeOne). Let me run prisma and memory adapter tests:
Assistant
Prisma and memory adapter tests pass. Let me run kysely and drizzle adapter tests (they may use in-memory sqlite):
Assistant
kysely and drizzle adapter tests pass. Let me run the better-auth plugin tests that consume single-use values / counters (two-factor, email-otp, one-time-token, api-key) to verify the fallback changes don't regress:
Assistant
All pass (167 tests). Let me run the api-key plugin (uses
incrementOnefor quota) and the test/unit integration tests:Assistant
Let me see the api-key test failure detail:
Assistant
The api-key tests fail to resolve
better-auth/test— the better-auth package isn't built (subpath exports point to dist). This is a test-infrastructure issue, not my change. Let me build better-auth (without dts) so its subpath exports resolve:Assistant
better-auth built. Let me re-run the api-key tests:
Assistant
api-key's org-api-key test (10 tests, uses
incrementOne) passes; the other uses postgres (environmental). Let me run the test/unit integration tests:Assistant
All passing. Let me do a TypeScript typecheck on the core package to verify my type changes compile cleanly:
Assistant
tsc typecheck passes. Let me add a changeset following the repo's convention. Let me look at an existing changeset format:
Assistant
The
rate-limit-atomic-consume.mddoesn't exist anymore (probably consumed). Let me look at an existing one to see format.Assistant
Let me create a changeset covering the affected packages (
@better-auth/coreandbetter-authare in the fixed group):Assistant
Let me review the full git diff and status to ensure correctness and no leftover temp files:
Assistant
dist is gitignored, so builds won't be submitted. Let me do a final review of the diff:
Assistant
The diff looks good. Let me run biome formatter check on the changed files to ensure formatting compliance:
Assistant
Biome wants some lines collapsed. Let me apply biome format to the changed files:
Assistant
Biome format applied. Let me run biome's full check (lint + format) on the changed files:
Assistant
Biome wants import ordering. Let me apply biome's safe fixes (including import organization):
Assistant
Biome check passes now. Let me verify the imports and re-run the core tests + re-validate the fix still works after formatting:
Assistant
Let me rebuild core dist (formatting changed source) and re-run key tests to confirm everything still works:
Assistant
Let me re-run the key better-auth tests after the core rebuild:
Assistant
All pass (83 tests). Let me do a final re-validation of the actual deadlock fix with a quick repro, then remove it:
Assistant
The fix works after formatting. Let me do a final git status to confirm only intended files are modified and no temp files remain:
Assistant
Clean — only the three source files and the changeset are modified. Let me verify the built dist includes the new export (build sanity):
Assistant
Everything is in place and validated. Let me do a final summary review of the complete diff:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.