Repository navigation
fix(storage-postgres): acquire saveTokenPair transaction asynchronously to avoid DbLoop deadlock - #15
Merged
Conversation
…ly to avoid DbLoop deadlock saveTokenPair() used the blocking DbClient::newTransaction() overload, but it is reached from inside DB result callbacks (e.g. the token endpoint's device-code flow issues tokens from within PgConnection::handleRead on a DbLoop thread). The blocking overload waits on a future that only the DB event loops themselves can fulfill, so calling it there stalls the loop it runs on. With two concurrent device-code redemptions occupying both DbLoop threads, BEGIN could never be sent and the whole process deadlocked -- observed as ctest hanging forever at the OAuth2Tests binary (first hit by Integration_P1_DeviceCode_ConcurrentRedemption_OnlyOneSucceeds, confirmed via GDB thread dump showing both DbLoops futex-waiting inside DbClientImpl::newTransaction()). Switch to newTransactionAsync() + Transaction::setCommitCallback(). Semantics are preserved: both INSERTs stay in one transaction, the caller callback still fires only after COMMIT, and the invokeOnce guard is unchanged. A transaction-acquisition timeout (null transPtr) now logs and invokes the callback instead of waiting forever. Verified on WSL (linux-release, live PostgreSQL + Redis): full authforge-tests run passes -- 56609 assertions in 290 test cases, no hang.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
wangrh0909
approved these changes
Aug 3, 2026
voidvec
added a commit
that referenced
this pull request
Aug 30, 2026
…loor, bootstrap self-heal, review cleanups Address PR #141 review (1 must-fix, 8 should-fix, quick considers): - #1 consent_csrf declared as a required query parameter in openapi.yaml and the C++ endpoint doc registration; apps/server/docs/api/openapi.json regenerated from a live server run; Python/Go clients regenerated. - #2 nonce one-shot is now atomic: the find/verify/erase sequence is serialized by a process-wide mutex (consent traffic is tiny; in-process session storage). - #3 identity AuthService no longer captures this in the async validateUser callback — the legacy-hash policy flag is value-captured (db-operations rule 4). - #4/#12 AdminBootstrapper reworked as ensure-* steps: an existing admin user row is reused and role/mapping completed (partial failures self-heal on restart); the random password is printed only after the insert succeeded; a mapping failure no longer reports created=true. - #5 POST /api/admin/users enforces auth.min_password_length (VALIDATION_PASSWORD_TOO_SHORT) — closing the admin bypass. - #6 consent integration tests reworked: missing-nonce now drives the real authorize-minted slot (400), deny-to-unregistered-uri (400, no Location) and deny-to-registered-uri (302 access_denied) branches are covered. - #7/#8 deployment.md: auto-bootstrap wording fixed, bogus ADMIN_SALT removed (PBKDF2 keeps salt empty); website i18n error table mirrored (3014/4007). - #9 main.cc bootstrap probes with backoff (5 attempts) and LOG_WARN on failure instead of a single silent 2s probe. - #13 unique-violation detection layered (SqlError 23505 -> constraint name -> english/zh localized text), mirroring the PostgresSocialAccountRepository pattern. - #11 gate-4 comment corrected; #15 CHANGELOG duplicate Unreleased merged; #17 AGENTS.md consent.csp entry removed. Considered-but-not-taken: #10 multi-slot nonces (tracked follow-up), #14 admin UI hardcode (server now enforces; hint stays), #18 MFA-pending session through consent (pre-existing authorize behavior, tracked).
voidvec
added a commit
that referenced
this pull request
Aug 30, 2026
…loor, bootstrap self-heal, review cleanups Address PR #141 review (1 must-fix, 8 should-fix, quick considers): - #1 consent_csrf declared as a required query parameter in openapi.yaml and the C++ endpoint doc registration; apps/server/docs/api/openapi.json regenerated from a live server run; Python/Go clients regenerated. - #2 nonce one-shot is now atomic: the find/verify/erase sequence is serialized by a process-wide mutex (consent traffic is tiny; in-process session storage). - #3 identity AuthService no longer captures this in the async validateUser callback — the legacy-hash policy flag is value-captured (db-operations rule 4). - #4/#12 AdminBootstrapper reworked as ensure-* steps: an existing admin user row is reused and role/mapping completed (partial failures self-heal on restart); the random password is printed only after the insert succeeded; a mapping failure no longer reports created=true. - #5 POST /api/admin/users enforces auth.min_password_length (VALIDATION_PASSWORD_TOO_SHORT) — closing the admin bypass. - #6 consent integration tests reworked: missing-nonce now drives the real authorize-minted slot (400), deny-to-unregistered-uri (400, no Location) and deny-to-registered-uri (302 access_denied) branches are covered. - #7/#8 deployment.md: auto-bootstrap wording fixed, bogus ADMIN_SALT removed (PBKDF2 keeps salt empty); website i18n error table mirrored (3014/4007). - #9 main.cc bootstrap probes with backoff (5 attempts) and LOG_WARN on failure instead of a single silent 2s probe. - #13 unique-violation detection layered (SqlError 23505 -> constraint name -> english/zh localized text), mirroring the PostgresSocialAccountRepository pattern. - #11 gate-4 comment corrected; #15 CHANGELOG duplicate Unreleased merged; #17 AGENTS.md consent.csp entry removed. Considered-but-not-taken: #10 multi-slot nonces (tracked follow-up), #14 admin UI hardcode (server now enforces; hint stays), #18 MFA-pending session through consent (pre-existing authorize behavior, tracked).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes a hard deadlock that made local test runs (
test.shon WSL/Linux) hang forever at CTest #248OAuth2Tests, right afterStart 248with no further output.Root cause
PostgresTokenRepository::saveTokenPair()used the blockingDbClient::newTransaction()overload, but it is reached from inside DB result callbacks — the token endpoint's device-code flow issues tokens from withinPgConnection::handleRead()on a DbLoop thread.The blocking overload waits on a future that only the DB event loops themselves can fulfill, so calling it on a DbLoop thread stalls that very loop. When
Integration_P1_DeviceCode_ConcurrentRedemption_OnlyOneSucceedsfires two concurrent device-code redemptions, both DbLoop threads enter this path simultaneously,BEGINcan never be sent to Postgres, and every subsequent DB operation in the process blocks forever. Since theOAuth2Testsctest entry has noTIMEOUTproperty, ctest waits indefinitely.Confirmed with a GDB thread dump of the hung process: both
DbLoopthreads futex-waiting insideDbClientImpl::newTransaction()undersaveTokenPair, main thread stuck in the next test case'sexecSql()future wait.Fix
Switch to
newTransactionAsync()and install the commit callback viaTransaction::setCommitCallback(). Original semantics are fully preserved:invokeOncereentrancy guard is unchanged.transPtr == nullptr) logs an error and invokes the callback instead of waiting forever.Other blocking
newTransaction()call sites were audited and left alone —SchemaManager.cc(startup migration, main thread) andClientManagementService.cc(HTTP IO thread) never run on a DbLoop thread, so they cannot self-deadlock.Verification
Full
authforge-testsbinary on WSL (linux-release preset, live PostgreSQL + Redis):Previously the run always hung at the device-code concurrency test; now the whole suite completes and exits normally.
Follow-up (not in this PR)
TIMEOUTproperty to theOAuth2Testsentry so any future in-process hang fails fast instead of blockingtest.shindefinitely.