fix: pgxpool deadlock on context cancellation — release semaphore immediately - #5
Open
johneapen80 wants to merge 1 commit into
Open
Conversation
Fixes concurrent context cancellation + semaphore contention causing pool to livelock. Two-part fix: 1. puddle/pool.go acquire(): check ctx.Done() after semaphore acquire to prevent goroutine leak when context is canceled between TryAcquire success and resource creation. 2. pgxpool/pool.go Acquire(): check ctx.Err() between retry iterations so a cancelled context terminates the retry loop immediately instead of cycling through all maxConns attempts. Includes regression test TestPoolAcquireStressCancelContention that exercises high-concurrency acquire with rapid context cancellation.
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.
Fixes deadlock and goroutine leak in pgxpool.Acquire() on context cancellation.
Root cause: When context is cancelled after TryAcquire succeeds but before resource creation completes, the semaphore is held indefinitely — blocking all future acquires.
Fix: Added ctx.Done() check after TryAcquire succeeds. If context is cancelled, immediately release semaphore and return the context error. Also added ctx.Err() checks in retry loop after Destroy() calls for expired connections.
Test: TestPoolAcquireStressCancelContention — 30 goroutines × 10 attempts with 1-5ms timeouts against saturated pool (MaxSize=3). Verifies pool remains functional and stats are consistent after stress.
Closes #1