Connection pool can briefly exceed max_size when pooling is disabled under load
Mantenedores costumam responder em até 2 dias
@bewithgaurav já está trabalhando nisso.
Desde 21/9/2026.
Avaliação
- Dificuldade
- 4/5
- Tempo estimado
- 3-5 dias
- Facilidade para iniciantes
- 62/100
Direção de pesquisa
Leia mssql_python/pybind/connection/connection_pool.cpp, concentrando-se no tratamento de falha da Fase 3 de ConnectionPool::acquire, em closePools() e em ConnectionPool::close. Rastreie os caminhos de reserva e limpeza e, em seguida, inspecione como PR #678 alterou a construção de Connection. Está concluído quando um teste de regressão cobre a intercalação entre falha e desativação e as conexões físicas ativas nunca excedem max_size.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
Describe the bug
The connection pool can transiently exceed its configured max_size when pooling is disabled (or the process begins shutting down) while new physical connections are being opened concurrently. The pool's internal reserved-capacity counter (_current_size) can drift below the true number of live connections, after which the pool opens more physical connections than max_size allows. It is transient and self-corrects as connections close.
Root cause: _current_size is a bare counter with no record of which reservation a given decrement belongs to. The failed-open cleanup runs if (_current_size > 0) --_current_size, while a pool disable/close runs _current_size = 0. If a reset lands between a thread reserving a slot and that same thread's open failing, the thread's decrement cancels a different thread's live reservation instead of its own.
Exception message: none. This is a silent _current_size accounting drift, no exception or stack trace.
To reproduce
This is a rare timing race, so it is not deterministically reproducible from a plain script. It requires a new connection to fail to open at the exact moment pooling is disabled or the process is shutting down. The interleave that produces it, with max_size = 2:
import mssql_python
from concurrent.futures import ThreadPoolExecutor
mssql_python.pooling(max_size=2)
# 1. Thread A calls connect(), reserves a slot -> _current_size = 1,
# then starts opening a new physical connection (outside the pool lock).
# 2. Another thread disables pooling: closePools() sets _current_size = 0.
# 3. Thread B calls connect(), reserves the freed slot -> _current_size = 1.
# 4. Thread A's open fails (handle alloc / network error): its cleanup runs
# --_current_size -> 0, cancelling B's slot instead of A's.
# 5. Thread B's open succeeds, but _current_size now reads 0.
# 6. Further connect() calls see room and open past max_size.
Observable symptom while the count is drifted: more live sessions than the configured cap.
SELECT COUNT(*) FROM sys.dm_exec_sessions WHERE login_name = 'yourapp';
-- transiently returns 3 with max_size = 2
Expected behavior
The number of live physical connections should never exceed max_size, regardless of a connection-open failure racing a pooling disable or process shutdown.
Further technical details
Python version: any
SQL Server version: any
Operating system: any. The race is in the cross-platform C++ pool, not platform specific.
Additional context
Area: mssql_python/pybind/connection/connection_pool.cpp, the Phase 3 failure catch in ConnectionPool::acquire, plus closePools() and ConnectionPool::close.
Regression status: pre-existing for the connect()-failure path. PR #678 moved Connection construction out of _mutex (required to fix the #671 deadlock), which widens the same race to also cover constructor failures such as ODBC env init, handle allocation, and OOM. Raised during review of #678.
Proposed fix: give the pool a generation counter. close()/closePools() bumps it under the lock, a reserver snapshots it at ++_current_size, and the failure cleanup only decrements if the generation still matches. This makes the decrement attributable and closes both the constructor and connect paths. Roughly 6 to 8 lines plus a regression test that forces the interleave.
- Linguagem predominante
- Python
- Estrelas
- 478
- Forks
- 62
- Merge médio
- 3d 19min
- PRs com merge (30d)
- 28
Preparar o ambiente
Inicia o contêiner de desenvolvimento do projeto no navegador, com a sua própria conta do GitHub.
- Sem Dockerfile nem arquivo Docker Compose
- Tem um modelo de pull request
- Ler o guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de microsoft/mssql-python
-
area: bulk-copy triage needed
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 70/100
microsoft/mssql-python#843 · 1 comentário ·
Mantenedores costumam responder em até 2 dias
-
triage needed
Dificuldade 4/5 3-5 dias Facilidade para iniciantes 35/100
microsoft/mssql-python#846 · 1 comentário ·
Mantenedores costumam responder em até 2 dias
-
macOS: encrypted connections fail after Homebrew moved the `openssl` alias to `openssl@4`Talvez já em andamento @bewithgaurav assumiu há 14 dias. Abertaarea: packaging-platform bug triage needed
Dificuldade 4/5 3-5 dias Facilidade para iniciantes 55/100
microsoft/mssql-python#826 · 2 comentários · 1 responsável ·
Mantenedores costumam responder em até 2 dias
-
Announcement: mssql-python is coming to Django through mssql-django 2.0Talvez livre de novo @bewithgaurav assumiu há 41 dias e não há nenhum pull request aberto. Abertaannouncement
microsoft/mssql-python#748 · 1 responsável ·
Mantenedores costumam responder em até 2 dias
-
Decimal in money range still string-binds on the executemany pathTalvez já em andamento @bewithgaurav assumiu há 23 dias. Abertaarea: data-types bug triage done under development
Dificuldade 4/5 3-5 dias Facilidade para iniciantes 48/100
microsoft/mssql-python#745 · 1 comentário · 1 responsável ·
Mantenedores costumam responder em até 2 dias
Todas as issues de microsoft/mssql-python
Issues semelhantes
-
customer-reported question
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 62/100
Azure/azure-sdk-for-python#49548 · 1 comentário · 1 reação ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 88/100
btclib-org/btclib-wallet#409 ·
Mantenedores costumam responder em até 1 dia
-
Phase 2 PSA Capability & Career Profile
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 62/100
bcgov/digital-journeys#2310 ·
-
bug good first issue
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 78/100
fastmachinelearning/hls4ml#1582 ·
Mantenedores costumam responder em até 3 dias
-
Sort modelsAbertaenhancement good first issue
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 62/100
Mantenedores costumam responder em até 1 dia