Skip to content

fix(storage-postgres): acquire saveTokenPair transaction asynchronously to avoid DbLoop deadlock - #15

Merged
voidvec merged 1 commit into
masterfrom
fix/save-token-pair-dbloop-deadlock
Aug 3, 2026
Merged

voidvec merged 1 commit into
masterfrom
fix/save-token-pair-dbloop-deadlock

Conversation

@voidvec

@voidvec voidvec commented Jul 31, 2026

Copy link
Copy Markdown
Owner

Summary

Fixes a hard deadlock that made local test runs (test.sh on WSL/Linux) hang forever at CTest #248 OAuth2Tests, right after Start 248 with no further output.

Root cause

PostgresTokenRepository::saveTokenPair() used the blocking DbClient::newTransaction() overload, but it is reached from inside DB result callbacks — 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 on a DbLoop thread stalls that very loop. When Integration_P1_DeviceCode_ConcurrentRedemption_OnlyOneSucceeds fires two concurrent device-code redemptions, both DbLoop threads enter this path simultaneously, BEGIN can never be sent to Postgres, and every subsequent DB operation in the process blocks forever. Since the OAuth2Tests ctest entry has no TIMEOUT property, ctest waits indefinitely.

Confirmed with a GDB thread dump of the hung process: both DbLoop threads futex-waiting inside DbClientImpl::newTransaction() under saveTokenPair, main thread stuck in the next test case's execSql() future wait.

Fix

Switch to newTransactionAsync() and install the commit callback via Transaction::setCommitCallback(). Original semantics are fully preserved:

  • Both INSERTs remain in a single transaction (atomicity unchanged).
  • The caller's callback still fires only after COMMIT (the earlier MVCC race fix is untouched).
  • The invokeOnce reentrancy guard is unchanged.
  • New: transaction-acquisition timeout (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) and ClientManagementService.cc (HTTP IO thread) never run on a DbLoop thread, so they cannot self-deadlock.

Verification

Full authforge-tests binary on WSL (linux-release preset, live PostgreSQL + Redis):

All tests passed (56609 assertions in 290 tests cases)
test::run() completed with status: 0

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)

  • Add a ctest TIMEOUT property to the OAuth2Tests entry so any future in-process hang fails fast instead of blocking test.sh indefinitely.

…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.
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@voidvec
voidvec requested a review from wangrh0909 August 1, 2026 15:42
@voidvec
voidvec merged commit 2db5216 into master Aug 3, 2026
8 checks passed
@voidvec
voidvec deleted the fix/save-token-pair-dbloop-deadlock branch August 4, 2026 10:11
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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants