Skip to content

FEAT: add native query cancellation foundations - #911

Merged
Jahnvi Thakkar (jahnvi480) merged 6 commits into
mainfrom
jahnvi/cancellation-native-foundations
Nov 24, 2026
Merged

Jahnvi Thakkar (jahnvi480) merged 6 commits into
mainfrom
jahnvi/cancellation-native-foundations

Conversation

@jahnvi480

Copy link
Copy Markdown
Contributor

Work Item / Issue Reference

N/A; using the GitHub issue reference below.

GitHub Issue: #424


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; legacy free() is unchanged.
  • Native 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.
  • Extend the existing test-only interposition map with SQLFreeHandle; normal Release builds expose no pointer controls. Document the focused validation command and the requirement to serialize these primitives against active use.

Extracted selected cleanup/retirement hunks from source snapshot 88f01a77a668d6a3f8b45ccb2b501854a1d6cee2, based on 52f30011b0b0229544cc50a8ef9f8ca0fb3d0e65 (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 x64 and incremental cmake --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-push and git diff --check: passed.

python above 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.

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>
Copilot AI balanced review requested due to automatic review settings November 23, 2026 12:36
@github-actions github-actions Bot added the pr-size: medium Moderate update size label Nov 23, 2026
@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

PR Performance Report

✅ No regression detected

No 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 diagnostics

Phase 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 timings

Unix / SQL Server 2022

Database task Before After Paired change Result
Connection opening 10.399 ms 10.387 ms -0.2% no signal
SELECT queries 1.004 ms 1.182 ms +10.6% no signal
Row insertion 30.692 ms 31.166 ms +0.8% no signal
Executemany inserts 156.342 ms 161.073 ms +3.8% no signal
Fetch-all queries 120.642 ms 120.387 ms +0.7% no signal
Row-by-row fetching 4.934 ms 5.020 ms +1.3% no signal
Batched row fetching 118.154 ms 116.672 ms -1.3% no signal
Transaction commit and rollback 105.878 ms 105.781 ms +1.5% no signal
Arrow row fetching 88.765 ms 89.287 ms +1.2% no signal
100,000-row insertion 358.590 ms 362.961 ms +1.2% no signal
Row fetching in batches of 100 119.650 ms 124.261 ms +5.1% no signal
Row fetching in batches of 10,000 138.083 ms 128.587 ms -10.4% no signal
Repeated positional queries 32.837 ms 32.445 ms -1.5% no signal
Repeated named-parameter queries 33.563 ms 33.013 ms -1.9% no signal
Legacy 100,000-row insertion 288.916 ms 269.340 ms -6.8% no signal
Insertion with explicit input sizes 414.784 ms 426.852 ms +0.7% no signal
Joined aggregation queries 181.816 ms 182.117 ms -0.5% no signal
Large joined-result fetching 191.782 ms 193.292 ms +0.8% no signal
1.2-million-row fetching 3509.759 ms 3489.488 ms -0.4% no signal
Common table expression queries 5.487 ms 5.363 ms -0.7% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.646 ms 1.780 ms +0.1% no signal
10,000 scalar values / fetchval() (debug disabled) 16.771 ms 16.731 ms -1.3% no signal
10,000 output-converted rows / fetchall() 19.420 ms 19.617 ms +0.3% no signal
10,000 output-converted rows / fetchmany(1000) 23.480 ms 23.035 ms -1.9% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 24.366 ms 24.366 ms -0.1% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 31.467 ms 31.592 ms +0.4% no signal

Unix / SQL Server 2025

Database task Before After Paired change Result
Connection opening 81.490 ms 80.807 ms -0.8% no signal
SELECT queries 0.984 ms 1.001 ms +0.8% no signal
Row insertion 30.480 ms 30.607 ms +0.3% no signal
Executemany inserts 149.545 ms 149.776 ms +0.7% no signal
Fetch-all queries 119.890 ms 121.241 ms +1.1% no signal
Row-by-row fetching 4.899 ms 4.936 ms +0.7% no signal
Batched row fetching 119.686 ms 117.186 ms -3.0% no signal
Transaction commit and rollback 105.942 ms 106.615 ms +0.7% no signal
Arrow row fetching 87.095 ms 89.940 ms +2.5% no signal
100,000-row insertion 364.617 ms 353.532 ms +1.5% no signal
Row fetching in batches of 100 123.356 ms 121.003 ms -1.9% no signal
Row fetching in batches of 10,000 124.892 ms 131.481 ms +1.7% no signal
Repeated positional queries 31.588 ms 31.776 ms +1.3% no signal
Repeated named-parameter queries 31.707 ms 33.075 ms +1.5% no signal
Legacy 100,000-row insertion 274.603 ms 267.968 ms +0.7% no signal
Insertion with explicit input sizes 419.676 ms 421.838 ms -0.4% no signal
Joined aggregation queries 160.682 ms 162.492 ms +1.2% no signal
Large joined-result fetching 187.161 ms 189.252 ms +1.2% no signal
1.2-million-row fetching 3498.768 ms 3447.228 ms -1.0% no signal
Common table expression queries 5.143 ms 5.124 ms -1.3% no signal
256 KiB VARCHAR(MAX) / fetchall() 2.058 ms 2.095 ms +5.8% no signal
10,000 scalar values / fetchval() (debug disabled) 16.277 ms 16.496 ms +1.5% no signal
10,000 output-converted rows / fetchall() 19.201 ms 19.237 ms +0.3% no signal
10,000 output-converted rows / fetchmany(1000) 22.814 ms 23.192 ms +1.6% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 24.403 ms 23.935 ms -1.5% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 31.000 ms 31.498 ms +1.5% no signal
Build and measurement details

ADO build 194682

PR head: 42e0bd339c1a74de8f850a70dd1ee433a2869120
Base: b327fbb07be040f5e8be4ac2e28400a664bfc331
Measured merge: e70dc62b78195ee696288a624ca0d1b5df6bd53e

  • Unix / SQL Server 2022: Python 3.12.3, x86_64, SQL 16.0.4325.4; 5 paired comparisons and 1 warmup.
  • Unix / SQL Server 2025: Python 3.12.3, x86_64, SQL 17.0.5065.9; 5 paired comparisons and 1 warmup.

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 profiler-* artifacts.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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

@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

📊 Code Coverage Report

🔥 Diff Coverage

65%


🎯 Overall Coverage

86%


📈 Total Lines Covered: 12214 out of 14163
📁 Project: mssql-python


Diff Coverage

Diff: main...HEAD, staged and unstaged changes

  • mssql_python/pybind/connection/connection.cpp (66.7%): Missing lines 1019-1020
  • mssql_python/pybind/ddbc_bindings.cpp (64.7%): Missing lines 1778,1786-1787,1804,1818-1819

Summary

  • Total: 23 lines
  • Missing: 8 lines
  • Coverage: 65%

mssql_python/pybind/connection/connection.cpp

Lines 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.cpp

Lines 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

⚙️ Build Summary 📋 Coverage Details

View Azure DevOps Build

Browse Full Coverage Report

Copilot AI balanced review requested due to automatic review settings November 23, 2026 13:41

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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

Copilot AI balanced review requested due to automatic review settings November 24, 2026 07:08

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The pooling test bypasses the compiled interposition-control requirement on Linux/macOS, silently accepting a missing fault-enabled build even when interposition was explicitly requested.

1 open issue

Review effort: Balanced

Comment thread tests/test_009_pooling.py Resolved
Copilot AI balanced review requested due to automatic review settings November 24, 2026 09:00
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>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The cleanup retry masks the actual diagnostic with an invalid-handle error when retained parameter buffers cause get() to return null despite the native handle remaining live.

2 open issues

Review effort: Balanced

Comment thread mssql_python/pybind/ddbc_bindings.cpp Resolved
Copilot AI balanced review requested due to automatic review settings November 24, 2026 09:05

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 09:11

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@jahnvi480
Jahnvi Thakkar (jahnvi480) merged commit 389a318 into main Nov 24, 2026
38 checks passed
Jahnvi Thakkar (jahnvi480) added a commit that referenced this pull request Nov 27, 2026
### 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-size: medium Moderate update size

3 participants