Repository navigation
FEAT: add native query cancellation foundations - #911
Conversation
Add checked idle statement release and explicit physical connection retirement as internal prerequisites. Keep public cancellation, operation admission and fetch paths unchanged. Cover mapped cleanup errors and pooled/unpooled retirement in isolated SQL and native tests. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
PR Performance Report✅ No regression detectedNo consistent slowdowns detected across all 2 environments. 0 IMPROVEMENTS 0 SLOWDOWNS 2/2 ENVIRONMENTS Coverage: 2 of 2 environments completed. Advisory result; does not block merging. Performance diagnosticsPhase times are inclusive diagnostics and must not be added together. They identify where measured time changed, not why it changed. No affected phases or call-count changes were recorded. All database tasks and timingsUnix / SQL Server 2022
Unix / SQL Server 2025
Build and measurement detailsPR head:
A consistent change requires more than 20% median paired movement, at least 1 ms between the median runtimes, and at least 80% of pairs exceeding the relative threshold in the same direction. A slowdown without enough pair agreement is reported as inconsistent. The displayed change is the median of paired before-and-after ratios. It is not recalculated from the two displayed median runtimes. Both revisions use profiling-enabled builds on the same agent and database, with alternating order and discarded warmups. Results are diagnostic and do not represent production-wheel latency. Raw samples and logs are attached to the ADO run as |
There was a problem hiding this comment.
🔵 Needs a closer look
Teardown safety requires cross-platform runtime validation of native handle cleanup, retirement, and diagnostic fault injection, but supplied evidence covers only Windows AMD64.
No open issues 🎉
What changed in this PR
Adds internal native cleanup and connection-retirement primitives as prerequisites for query cancellation in #424. This does not implement cancellation or expose a public cancellation API.
Changes:
- Adds checked idle-handle release with DB-API error mapping and explicit connection retirement that bypasses pool reuse.
- Adds native and subprocess tests for cleanup diagnostics, surviving statement aliases, pending work, and pool capacity.
- Updates internal stubs and documents focused validation and caller serialization requirements.
| File | Description |
|---|---|
tests/test_009_pooling.py |
Adds isolated cleanup, diagnostics, and retirement tests. |
tests/native/pool_sanitation.cpp |
Tests discard behavior, alias invalidation, and capacity recovery. |
mssql_python/pybind/ddbc_bindings.cpp |
Binds cleanup primitives and extends test-only pointer access. |
mssql_python/pybind/connection/connection.h |
Declares native connection discard. |
mssql_python/pybind/connection/connection.cpp |
Implements discard through existing retirement logic. |
mssql_python/_ddbc_types.pyi |
Adds internal cleanup and discard signatures. |
.github/prompts/build-ddbc.prompt.md |
Documents cleanup validation and serialized-use requirements. |
Review effort: Balanced
📊 Code Coverage Report
Diff CoverageDiff: main...HEAD, staged and unstaged changes
Summary
mssql_python/pybind/connection/connection.cppLines 1015-1024 1015 if (_conn) {
1016 ConnectionPoolManager::getInstance().discardConnection(_originPool, _conn);
1017 _conn = nullptr;
1018 }
! 1019 }
! 1020
1021 void ConnectionHandle::commit() {
1022 PERF_TIMER("ConnectionHandle::commit");
1023 if (!_conn) {
1024 ThrowStdException("Connection object is not initialized");mssql_python/pybind/ddbc_bindings.cppLines 1774-1782 1774 void SqlHandle::free() {
1775 freeHandle();
1776 }
1777
! 1778 void SqlHandle::freeChecked() {
1779 ErrorInfo error;
1780 SQLRETURN result = freeHandle(&error);
1781 if (!SQL_SUCCEEDED(result)) {
1782 py::module_::import("mssql_python.exceptions").attr("raise_exception")(Lines 1782-1791 1782 py::module_::import("mssql_python.exceptions").attr("raise_exception")(
1783 error.sqlState.empty() ? "HY000" : error.sqlState, error.ddbcErrorMsg);
1784 }
1785 }
! 1786
! 1787 SQLRETURN SqlHandle::freeHandle(ErrorInfo* error) {
1788 PERF_TIMER("SqlHandle::free");
1789 resultMetadata.clear();
1790 bool pythonShuttingDown = is_python_finalizing();
1791 bool skipDuringShutdown = _type == SQL_HANDLE_STMT || _type == SQL_HANDLE_DBC;Lines 1800-1808 1800 _handle = nullptr;
1801 return SQL_SUCCESS;
1802 }
1803
! 1804 auto freeNative = [this, error]() -> SQLRETURN {
1805 auto cleanupLock = lockForCleanup();
1806 if (!_handle) {
1807 if (error) *error = SQLReadError(_type, nullptr, SQL_INVALID_HANDLE);
1808 return SQL_INVALID_HANDLE;Lines 1814-1823 1814 }
1815 if (SQL_SUCCEEDED(ret)) {
1816 _handle = nullptr;
1817 if (_failedParameterBuffers) _failedParameterBuffers->release();
! 1818 } else {
! 1819 if (_type == SQL_HANDLE_STMT && _cleanupState) {
1820 _cleanupState->childFreeFailed = true;
1821 }
1822 // get() hides poisoned statements; cleanup still owns their raw handle.
1823 if (error) *error = SQLReadError(_type, _handle, ret);📋 Files Needing Attention📉 Files with overall lowest coverage (click to expand)mssql_python.pybind.performance_counter.hpp: 0.7%
mssql_python.pybind.logger_bridge.cpp: 57.9%
mssql_python.pybind.ddbc_bindings.h: 64.8%
mssql_python.pybind.logger_bridge.hpp: 70.8%
mssql_python._native_fetch.py: 77.7%
mssql_python.__init__.py: 81.2%
mssql_python.pybind.ddbc_bindings.cpp: 81.2%
mssql_python.pybind.row_mapping_cache.hpp: 81.5%
mssql_python.pybind.connection.connection_pool.cpp: 83.7%
mssql_python.logging.py: 86.8%🔗 Quick Links
|
There was a problem hiding this comment.
🔵 Needs a closer look
Native ODBC handle lifetime and connection-retirement behavior require cross-platform runtime validation for both providers, but supplied results cover only Windows AMD64 and this review environment cannot run the necessary tests.
No open issues 🎉
Review effort: Balanced
Gate cleanup fault subprocesses on the compiled interposition map regardless of OS. Cover Linux, macOS and Windows missing-control failure/skip behavior. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
Native-handle retirement and cleanup failure paths need human runtime validation because live-SQL checks, non-Windows/other-architecture coverage, and the full runtime suite remain unverified.
1 open issue
1 resolved since last review
Review effort: Balanced
Capture failed native release diagnostics from the raw handle under the cleanup gate, while keeping poisoned handles hidden from execution. Cover failed retries, retained parameter lifetime and eventual free/discard. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
Native cleanup crosses GIL, ODBC, and retained-buffer lifetime boundaries, while Windows-only runtime validation leaves cross-platform teardown and diagnostics requiring human confirmation.
No open issues 🎉
1 resolved since last review
Review effort: Balanced
Sumit Sarabhai (sumitmsft)
left a comment
There was a problem hiding this comment.
Reviewed the PR for correctness, security, reliability, performance, test coverage, repository conventions, and applicable architecture and design specifications. No actionable issues were identified. The implementation is consistent with repository standards and the applicable approved design requirements.
Recommendation: Approve
### Work Item / Issue Reference <!-- IMPORTANT: Please follow the PR template guidelines below. For mssql-python maintainers: Insert your ADO Work Item ID below For external contributors: Insert Github Issue number below Only one reference is required - either GitHub issue OR ADO Work Item. --> <!-- mssql-python maintainers: ADO Work Item --> > [AB#50319](https://sqlclientdrivers.visualstudio.com/c6d89619-62de-46a0-8b46-70b92a84d85e/_workitems/edit/50319) <!-- External contributors: GitHub Issue --> ------------------------------------------------------------------- ### Summary <!-- Insert your summary of changes below. Minimum 10 characters required. --> Prepare mssql-python 1.19.0. Bump the package version in `mssql_python/__init__.py` and `setup.py`, and replace the previous release highlights in `PyPI_Description.md`. #### Enhancements - Optional connection retry policy for transient failures during connection initialization (#751). - Table-valued parameter definitions and synchronous execution through the default ODBC provider (#789). - Optional SQLSTATE and native error number attributes on DB-API exceptions (#909, #913). - Best-effort synchronous cursor cancellation with operation-scoped requests and checked recovery (#911, #915). - POSIX native binary hardening (#810). #### Bug Fixes - Lossless `executemany` inference for Unicode, Decimal, mixed-type batches, and embedded/trailing NULs (#907). - Numeric binding for auto-detected money-range Decimal batches (#752). - Restore Korean VARCHAR conversion fidelity in manylinux packages (#910). #### Release status and gates - ADO-GitHub synchronization completed into ADO `main` via [ADO PR !9120](https://sqlclientdrivers.visualstudio.com/mssql-python/_git/mssql-python/pullrequest/9120). - Ready for reviewer approval. The equivalent ADO release PR follows approval of this GitHub PR. - Do not merge this release PR until the required PyPI and Conda publication and verification gates are complete. - Release builds, publication, and release qualification remain outstanding; marking this PR ready for review does not authorize publication or merging. #### Validation - `.\.venv\Scripts\python.exe -m pre_commit run black-check --all-files --hook-stage pre-push` - passed. - `git diff --check` - passed. - Source-only checks verified matching `1.19.0` version declarations, one current "What's new" section, and the agreed description scope. - Native build and runtime pytest were not run for this version/description-only change; release qualification remains required. <!-- ### PR Title Guide > For feature requests FEAT: (short-description) > For non-feature requests like test case updates, config updates , dependency updates etc CHORE: (short-description) > For Fix requests FIX: (short-description) > For doc update requests DOC: (short-description) > For Formatting, indentation, or styling update STYLE: (short-description) > For Refactor, without any feature changes REFACTOR: (short-description) > For performance improvements PERF: (short-description) > For AI tooling, agents, skills, prompts, or AI-assisted development workflows AI: (short-description) > For release related changes, without any feature changes RELEASE: #<RELEASE_VERSION> (short-description) ### Contribution Guidelines External contributors: - Create a GitHub issue first: https://github.com/microsoft/mssql-python/issues/new - Link the GitHub issue in the "GitHub Issue" section above - Follow the PR title format and provide a meaningful summary mssql-python maintainers: - Create an ADO Work Item following internal processes - Link the ADO Work Item in the "ADO Work Item" section above - Follow the PR title format and provide a meaningful summary --> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Work Item / Issue Reference
Summary
First prerequisite layer only: add internal checked idle-statement release and explicit physical connection retirement. This PR does not implement query cancellation or expose a public cancellation API.
SqlHandle._free_checked()preserves cleanup diagnostics through the existing DB-API exception mapping and uses HY000 when no SQLSTATE is available; legacyfree()is unchanged.Connection.discard()reuses existing retirement logic instead of returning an unsafe physical connection to its pool. Matching internal stubs and focused native/subprocess tests cover failure diagnostics, surviving statement aliases, pending work, pooled/unpooled retirement, and size-one pool capacity.Extracted selected cleanup/retirement hunks from source snapshot
88f01a77a668d6a3f8b45ccb2b501854a1d6cee2, based on52f30011b0b0229544cc50a8ef9f8ca0fb3d0e65(also this branch's main base). No operation tokens, admission fences, Python wrapper integration, or execute/fetch hot-path changes are included.Validation on Windows AMD64, Python 3.13.17, SQL Server 2019 Express, using this worktree's own extension:
build.bat x64and incrementalcmake --build S:\mssql_python\pybind\build\x64\py313 --config Release --target ddbc_bindings pool_sanitation_tests --parallel 2 -- /verbosity:minimal: passed. Built with profiling/native-fetch fault controls OFF; isolated diagnostic tests used Arrow test interposition ON, then rebuilt with it OFF and verified the final local Release import.ctest --test-dir S:\mssql_python\pybind\build\x64\py313 -C Release --output-on-failure --no-tests=error --timeout 120 -R '^pool_sanitation$': passed (93 native scenarios).python -m pytest tests\test_009_pooling.py -k test_native_checked_cleanup -q --tb=short, with test interposition ON: 4 passed for each of msodbcsql18 and mssql-odbc. The two success/retirement tests first failed against the built base because these primitives did not exist.python -m pytest tests\test_009_pooling.py -k 'test_native_checked_cleanup or test_native_destructor or test_native_disconnect_with_concurrent_child_gc or test_unclosed_native_handle_destructor' -q --tb=short, with final Release controls OFF: 9 passed, 2 expected diagnostic-interposition skips for each provider; those skipped cases passed in the preceding fault build.python -m pytest tests\test_typing.py -m typing -q --tb=short: 4 passed.python -m pre_commit run black-check --all-files --hook-stage pre-pushandgit diff --check: passed.pythonabove denotes the approved development-venv interpreter; S: maps only this child worktree. Full runtime-suite and non-Windows/other-architecture execution were not run locally. No latency benchmark was run because existing execution/fetch paths are unchanged; this makes no no-regression claim about the integrated feature.Remaining layers: synchronous public cancellation with operation ownership/admission, completion fences and recovery integration (including repairing the integrated fetch-performance regression before shipping), then broader cross-platform delivery verification and usage guidance. Async Rust/TDS and bulk-copy cancellation remain out of scope. This prerequisite PR neither closes the issue nor ships the integrated feature.