Skip to content

FEAT: add synchronous cursor cancellation - #915

Merged
Jahnvi Thakkar (jahnvi480) merged 7 commits into
mainfrom
jahnvi/public-query-cancellation
Nov 26, 2026
Merged

Jahnvi Thakkar (jahnvi480) merged 7 commits into
mainfrom
jahnvi/public-query-cancellation

Conversation

@jahnvi480

Copy link
Copy Markdown
Contributor

Work Item / Issue Reference

N/A; using the GitHub issue reference below.

GitHub Issue: #424


Summary

Second dependent layer, targeting jahnvi/cancellation-native-foundations: expose synchronous Cursor.cancel() with operation identity, admission/completion fences, checked recovery, and fail-closed connection retirement. This is a draft for review, not shipping-ready.

  • Cancellation is always available, without an opt-in. Supported synchronous ODBC operations are execute/executemany, fetchone/fetchmany/fetchall/fetchval, row iteration, and nextset. Idle/completed calls preserve unread results; closed calls raise ProgrammingError. A captured request cannot affect a replacement operation.
  • Accepted cancellation abandons the current result. The worker normally raises OperationalError with driver_error == "Operation canceled" while preserving more specific primary errors. Cancellation is best effort, has no response deadline, and performs no implicit rollback or undo. Wait for owner completion before reuse.
  • Serialize connection admission and join SQLCancel before diagnostics, later native calls, or recovery. Competing execution, close, commit/rollback, and cursor creation fail fast during active ownership. Active catalog/scroll/Arrow/bulk-copy operations reject public cancellation; Rust/TDS async cancellation remains out of scope. SQLCancel stays optional and guarded.
  • Retain the Python fallback and native fetch policy/ownership protocol, DAE and NULL-introspection fences, checked statement recovery, and physical retirement without pooled return when cancellation/cleanup leaves uncertain state. Keep the tested three-owner finishUncaptured condition; no speculative ownership-count optimization is included.
  • Include the essential live-SQL, isolated race, stale-request, fault-diagnostic, completion-fence, recovery-allocation, and interruption tests here, plus public/internal stubs and usage documentation. Adapt directly dependent mock/call-count tests rather than moving safety tests to a later layer.

Extracted and three-way integrated source snapshot 88f01a77a668d6a3f8b45ccb2b501854a1d6cee2 (original source base 52f30011b0b0229544cc50a8ef9f8ca0fb3d0e65) onto verified parent tip 42e0bd339c1a74de8f850a70dd1ee433a2869120. Preserve the parent's checked cleanup/raw-handle diagnostics, physical retirement, native tests, and build guide. Preserve newer main TVP buffer-lifetime handling, generic streamed rows/rowcount aggregation, and UTF-16 LOB sizing. Adapt cancellation to the newer execute-in-progress guard and TVP/LOB boundaries; add LOB fence cases and exercise public cancellation during TVP streaming.

Unresolved performance blocker: prior matched ordinary Release measurements of the integrated feature found a repeatable single-column fetchone median paired regression of +10.2%, with all six pairs slower (+4.4% to +13.5%). fetchmany(1) remains a concern; other timings were highly variable. These are inherited integrated-feature measurements, not a new benchmark of this extracted branch. They have not been resolved or invalidated by the correctness checks below. No universal no-regression or fastest claim is made. Do not weaken completion fences or hold the GIL over blocking SQLGetData to hide the regression.

Validation on Windows AMD64, Python 3.13.17/MSVC 19.44, SQL Server 2019 Express, using this worktree's own package and compiled extension. python below denotes the approved development-venv interpreter. T: maps only this worktree; no other checkout or extension was modified.

  • build.bat x64: passed with ENABLE_PROFILING=ON and MSSQL_ARROW_TEST_INTERPOSITION=ON. Configured the separate fault build with cmake -S T:\mssql_python\pybind -B T:\mssql_python\pybind\build\x64\py313 -DENABLE_PROFILING=ON -DMSSQL_NATIVE_FETCH_TEST_FAULTS=ON -DMSSQL_ARROW_TEST_INTERPOSITION=ON: passed. cmake --build T:\mssql_python\pybind\build\x64\py313 --config Release --target ddbc_bindings pool_sanitation_tests --parallel 2 -- /verbosity:minimal: initially failed because the pool target was not enabled, after successfully building the extension; explicitly copied that extension into this package. Resolved setup with cmake -S T:\mssql_python\pybind -B T:\mssql_python\pybind\build\x64\py313 -DBUILD_NATIVE_POOL_TESTS=ON and cmake --build T:\mssql_python\pybind\build\x64\py313 --config Release --target pool_sanitation_tests --parallel 2 -- /verbosity:minimal: both passed.
  • Fault build, MSSQL_ARROW_TEST_INTERPOSITION=ON: python -m pytest tests\test_query_cancellation.py tests\test_native_fetch_dispatch.py tests\test_028_table_valued_parameters.py -q -rs --tb=short: 271 passed, 17 skipped, 1 deselected on msodbcsql18. python -m pytest tests\test_query_cancellation.py tests\test_native_fetch_dispatch.py -q -rs --tb=short: 219 passed, 16 skipped with MSSQL_PYTHON_NATIVE_PROVIDER=mssql-odbc. The 16 native-fetch skips require exported SQLFetch globals unavailable on Windows; the additional TVP skip requires TCP forwarding unavailable with this named instance. The deselected test is the default-excluded stress case. TVPs remain unsupported by the alternate provider.
  • Fault build, python -m pytest tests\test_004_cursor_arrow.py -k 'native_cancel_boundary or close_waits_for_batch or does_not_touch_reexecuted_result or ignores_replacement_statement or cancels_blocked_driver_fetch or close_retries_after_failed_attempt' -q --tb=short: 26 passed, 58 deselected for each provider.
  • python -m pytest tests\test_006_exceptions.py tests\test_020_bulkcopy_auth_cleanup.py tests\test_024_bulkcopy_arrow.py tests\test_004_cursor.py::test_executemany_decimal_numeric_override_coverage tests\test_013_encoding_decoding.py::test_lob_preserves_payload_nuls tests\test_017_spatial_types.py::test_large_udt_parameters tests\test_009_pooling.py -k 'not test_009_pooling or test_native_checked_cleanup or test_cursor_cyclic_finalizer_with_concurrent_native_disconnect' -q -rs --tb=short: 302 passed, 81 deselected on msodbcsql18 in the fault build.
  • Ordinary Release configuration: cmake -S T:\mssql_python\pybind -B T:\mssql_python\pybind\build\x64\py313 -DENABLE_PROFILING=OFF -DMSSQL_NATIVE_FETCH_TEST_FAULTS=OFF -DMSSQL_ARROW_TEST_INTERPOSITION=OFF and cmake --build T:\mssql_python\pybind\build\x64\py313 --config Release --target ddbc_bindings pool_sanitation_tests --parallel 2 -- /verbosity:minimal: passed. Explicitly copied the Release output only after fault-test processes finished. Verified own import, absent profiling/interposition APIs, and all three final cache flags OFF.
  • ctest --test-dir T:\mssql_python\pybind\build\x64\py313 -C Release --output-on-failure --no-tests=error --timeout 120 -R '^pool_sanitation$': 1 passed, in both fault and ordinary Release builds.
  • Ordinary Release, MSSQL_ARROW_TEST_INTERPOSITION=OFF: python -m pytest tests\test_query_cancellation.py tests\test_native_fetch_dispatch.py tests\test_028_table_valued_parameters.py -q -rs --tb=short: 211 passed, 77 skipped, 1 deselected on msodbcsql18. python -m pytest tests\test_query_cancellation.py tests\test_native_fetch_dispatch.py -q -rs --tb=short: 159 passed, 76 skipped on mssql-odbc. Release intentionally omits 53 cancellation-interposition cases and 7 native-fetch fault cases; these passed in the separate fault build. Other skips are the Windows exported-pointer/TCP restrictions above.
  • Ordinary Release, python -m pytest tests\test_004_cursor.py -k 'executemany_string_column or executemany_mixed_column or executemany_unicode_subclass or executemany_generated_batches or executemany_fallback or executemany_mixed_fallback' -q --tb=short: 116 passed, 644 deselected. Batch-vs-single-execution count assertions remain intact.
  • python -m pytest tests\test_008_auth.py::TestManagedIdentity::test_bulkcopy_path_preserves_user_assigned_msi_client_id -q --tb=short: 1 passed. python -m pytest tests\test_typing.py -m typing -q --tb=short: 7 passed.
  • python -m pre_commit run black-check --all-files --hook-stage pre-push and git diff --check: passed. Extraction-specific test expectation mismatches and the initial formatting change were corrected before the final gates.

The full runtime suite, full Arrow suite, non-Windows/other-architecture execution, new matched latency benchmarks, and broader delivery verification were not run here. Remaining work is performance repair and broader cross-platform/stress/delivery verification before shipping; no third layer is created by this PR. This PR does not merge the stack or close the issue.

@github-actions github-actions Bot added the pr-size: large Substantial code update label Nov 24, 2026
@jahnvi480
Jahnvi Thakkar (jahnvi480) marked this pull request as ready for review November 24, 2026 12:35
Integrate operation ownership, cancellation fences and fail-closed recovery as the second dependent layer. Preserve latest native cleanup and parameter-streaming behavior. Fetch performance remains a documented draft blocker.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@jahnvi480
Jahnvi Thakkar (jahnvi480) force-pushed the jahnvi/public-query-cancellation branch from a18be09 to 5692b4f Compare November 24, 2026 12:38
@jahnvi480
Jahnvi Thakkar (jahnvi480) changed the base branch from jahnvi/cancellation-native-foundations to main November 24, 2026 12:38
@jahnvi480
Jahnvi Thakkar (jahnvi480) changed the base branch from main to jahnvi/cancellation-native-foundations November 24, 2026 12:40
@jahnvi480
Jahnvi Thakkar (jahnvi480) changed the base branch from jahnvi/cancellation-native-foundations to main November 24, 2026 12:41
Match native visibility to pybind11 handles, preserve safety probes without profiling, assert fail-fast fetch reentry, and keep injection test IDs safe for Azure logging.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 14:01
@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

PR Performance Report

⚠️ Performance regression detected

1 database task consistently slowed down across 1 measured environment.

0 IMPROVEMENTS 1 SLOWDOWN 2/2 ENVIRONMENTS

Signal fingerprint

Database task Unix / SQL Server 2022
Row-by-row fetching 21.5% slower

The largest recorded phase increases for these tasks are shown below. Phase timings are supporting evidence, not root-cause proof.

Coverage: 2 of 2 environments completed. Advisory result; does not block merging.

Measured timings
Environment Database task Before After Change
Unix / SQL Server 2022 Row-by-row fetching 4.972 ms 6.035 ms +21.5%
Performance diagnostics

Phase times are inclusive diagnostics and must not be added together. They identify where measured time changed, not why it changed.

Unix / SQL Server 2022

SELECT queries: ddbc::FetchBatchData::SQLFetchScroll_call +0.002 ms; ddbc::FetchBatchData::cache_column_metadata +0.000 ms; ddbc::SQLDescribeCol::driver_call +0.000 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Row insertion: ddbc::BindParameters::SQLBindParameter_call +0.034 ms; ddbc::BindParameters +0.029 ms; py::execute::param_prep +0.017 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Executemany inserts: py::executemany::param_type_detection +0.072 ms; py::executemany::param_processing +0.031 ms; ddbc::BindParameterArray +0.026 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Row-by-row fetching: ddbc::FetchSingleRow +0.944 ms; ddbc::NativeCursor::fetch +0.935 ms; ddbc::SQLGetData_wrap +0.903 ms. Call changes: ddbc::SQLGetData::scalar_group (added, removed, or intermittent).
Transaction commit and rollback: py::execute::diag_records +0.061 ms; ddbc::SQLDescribeCol::driver_call +0.002 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Repeated positional queries: ddbc::NativeCursor::fallback +0.496 ms; py::execute::cpp_call +0.143 ms; ddbc::SQLExecute_wrap +0.130 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Repeated named-parameter queries: ddbc::NativeCursor::fallback +0.440 ms; py::execute::diag_records +0.031 ms; ddbc::FetchSingleRow +0.019 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Joined aggregation queries: ddbc::FetchBatchData::construct_rows +0.017 ms; ddbc::SQLDescribeCol_wrap +0.009 ms; ddbc::FetchAll_wrap +0.004 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Large joined-result fetching: ddbc::FetchAll_wrap +1.874 ms; ddbc::FetchBatchData +1.851 ms; py::fetchall::cpp_call +1.651 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
1.2-million-row fetching: ddbc::FetchBatchData::construct_rows +24.228 ms; py::fetchall::cpp_call +8.224 ms; ddbc::FetchBatchData::cache_column_metadata +0.106 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Common table expression queries: py::execute::cpp_call +0.190 ms; ddbc::SQLExecDirect_wrap +0.184 ms; py::execute::post_execute +0.031 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).

Unix / SQL Server 2025

SELECT queries: ddbc::FetchBatchData::SQLFetchScroll_call +0.026 ms; py::execute::post_execute +0.020 ms; ddbc::SQLExecDirect_wrap +0.017 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Row insertion: py::execute::cpp_call +0.238 ms; ddbc::SQLExecute_wrap +0.235 ms; ddbc::BindParameters +0.049 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Executemany inserts: py::executemany::param_conversion +1.539 ms; py::executemany::param_type_detection +0.507 ms; py::executemany::diag_records +0.002 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Row-by-row fetching: ddbc::NativeCursor::fetch +0.860 ms; ddbc::FetchSingleRow +0.832 ms; ddbc::SQLGetData_wrap +0.831 ms. Call changes: ddbc::SQLGetData::scalar_group (added, removed, or intermittent).
Transaction commit and rollback: ddbc::SQLExecDirect_wrap +0.048 ms; py::execute::diag_records +0.007 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Repeated positional queries: ddbc::NativeCursor::fallback +0.373 ms; py::execute::post_execute +0.096 ms; ddbc::FetchOne_wrap +0.037 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Repeated named-parameter queries: ddbc::NativeCursor::fallback +0.404 ms; py::execute::post_execute +0.074 ms; py::execute::diag_records +0.023 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Joined aggregation queries: ddbc::FetchBatchData::construct_rows +0.024 ms; py::execute::post_execute +0.013 ms; ddbc::FetchBatchData +0.008 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Large joined-result fetching: ddbc::FetchBatchData::construct_rows +1.327 ms; ddbc::SQLExecDirect_wrap +0.512 ms; py::execute::cpp_call +0.510 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).

2 additional diagnostic rows are available in the raw ADO artifacts.

All database tasks and timings

Unix / SQL Server 2022

Database task Before After Paired change Result
Connection opening 10.634 ms 10.646 ms +2.4% no signal
SELECT queries 1.021 ms 1.271 ms +24.5% no signal
Row insertion 31.114 ms 31.961 ms +2.1% no signal
Executemany inserts 164.037 ms 159.877 ms -0.2% no signal
Fetch-all queries 119.670 ms 120.314 ms +1.8% no signal
Row-by-row fetching 4.972 ms 6.035 ms +21.5% consistent slowdown
Batched row fetching 120.907 ms 119.309 ms -1.9% no signal
Transaction commit and rollback 106.586 ms 108.176 ms +0.8% no signal
Arrow row fetching 88.678 ms 91.136 ms +1.4% no signal
100,000-row insertion 361.120 ms 382.219 ms +2.3% no signal
Row fetching in batches of 100 120.843 ms 129.301 ms +7.0% no signal
Row fetching in batches of 10,000 141.188 ms 128.284 ms -9.9% no signal
Repeated positional queries 32.286 ms 33.658 ms +3.6% no signal
Repeated named-parameter queries 32.930 ms 33.722 ms +3.2% no signal
Legacy 100,000-row insertion 274.927 ms 279.086 ms +0.8% no signal
Insertion with explicit input sizes 424.256 ms 438.242 ms +1.1% no signal
Joined aggregation queries 177.647 ms 176.934 ms -0.4% no signal
Large joined-result fetching 194.838 ms 198.627 ms +0.4% no signal
1.2-million-row fetching 3492.862 ms 3501.745 ms +0.3% no signal
Common table expression queries 5.316 ms 5.711 ms +8.7% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.837 ms 1.330 ms -26.1% no signal
10,000 scalar values / fetchval() (debug disabled) 17.125 ms 19.388 ms +13.1% no signal
10,000 output-converted rows / fetchall() 20.080 ms 19.594 ms -0.9% no signal
10,000 output-converted rows / fetchmany(1000) 25.028 ms 25.697 ms +0.4% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 24.933 ms 28.165 ms +14.1% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 33.472 ms 34.234 ms +2.1% no signal

Unix / SQL Server 2025

Database task Before After Paired change Result
Connection opening 81.345 ms 82.246 ms +1.4% no signal
SELECT queries 1.060 ms 1.300 ms +23.9% no signal
Row insertion 30.804 ms 32.073 ms +4.1% no signal
Executemany inserts 153.548 ms 156.351 ms +1.9% no signal
Fetch-all queries 121.186 ms 121.935 ms +0.7% no signal
Row-by-row fetching 5.069 ms 6.071 ms +20.0% no signal
Batched row fetching 118.964 ms 119.012 ms +0.5% no signal
Transaction commit and rollback 106.868 ms 108.919 ms +1.7% no signal
Arrow row fetching 90.907 ms 90.023 ms -0.9% no signal
100,000-row insertion 377.574 ms 376.730 ms -0.5% no signal
Row fetching in batches of 100 122.203 ms 128.322 ms +5.7% no signal
Row fetching in batches of 10,000 129.703 ms 129.521 ms -0.5% no signal
Repeated positional queries 31.806 ms 33.172 ms +4.5% no signal
Repeated named-parameter queries 32.552 ms 33.611 ms +3.5% no signal
Legacy 100,000-row insertion 273.799 ms 274.556 ms +0.1% no signal
Insertion with explicit input sizes 435.135 ms 436.423 ms -1.1% no signal
Joined aggregation queries 167.264 ms 166.780 ms -0.3% no signal
Large joined-result fetching 194.132 ms 193.017 ms +1.1% no signal
1.2-million-row fetching 3548.640 ms 3541.417 ms -0.3% no signal
Common table expression queries 5.284 ms 5.528 ms +3.2% no signal
256 KiB VARCHAR(MAX) / fetchall() 2.056 ms 1.771 ms -15.7% no signal
10,000 scalar values / fetchval() (debug disabled) 17.741 ms 19.387 ms +11.2% no signal
10,000 output-converted rows / fetchall() 19.851 ms 20.247 ms -1.3% no signal
10,000 output-converted rows / fetchmany(1000) 24.226 ms 24.923 ms +0.3% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 25.063 ms 28.050 ms +9.8% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 33.145 ms 35.097 ms +8.0% no signal
Build and measurement details

ADO build 195028

PR head: 5a27f4b4183df0de0731ac2053f12bfc4f4448e0
Base: ee684d179f3cd68860bad17a9ff0ffeab9a49a07
Measured merge: eed40a5a40630d6d57a8c6f1d4247ccd5227c790

  • 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.

🟡 Changes recommended

The cancellation test fails on supported Python fallback paths, and close-path defects can retain substantial parameter memory or leave Arrow result cleanup incomplete.

3 open issues
What changed in this PR

Adds synchronous Cursor.cancel() for issue #424, connecting the Python API to native ODBC cancellation with operation ownership and recovery safeguards. This remains a draft; the reported fetch performance regression and broader platform validation are unresolved.

Changes:

  • Adds cancellation, connection admission guards, checked recovery, and retirement of connections left in uncertain state.
  • Integrates cancellation with native fetching, streamed parameters, and Python fallback paths.
  • Adds cancellation tests, updates dependent tests and type stubs, and documents usage and limitations.
File Description
tests/​test_typing.py Checks the public cancel() call shape.
tests/​test_query_cancellation.py Adds cancellation, race, recovery, and interruption coverage.
tests/​test_native_fetch_dispatch.py Tests token reuse and guarded fetch dispatch.
tests/​test_041_rs_nightly_selection.py Adds explicit parametrized test IDs.
tests/​test_028_table_valued_parameters.py Exercises public cancellation during TVP streaming.
tests/​test_024_bulkcopy_arrow.py Adds operation state to mock cursors.
tests/​test_020_bulkcopy_auth_cleanup.py Updates bulk-copy mocks for admission guards.
tests/​test_017_spatial_types.py Observes the internal execution path.
tests/​test_009_pooling.py Handles close rejection during active ownership.
tests/​test_008_auth.py Updates authentication mocks for operation state.
tests/​test_006_exceptions.py Checks internal cursor cleanup during connection close.
tests/​test_004_cursor.py Adapts execution spies and mock operation state.
README.md Documents cancellation behavior and limitations.
mssql_python/​pybind/​native_fetch.hpp Integrates native admission and cancellation ownership.
mssql_python/​pybind/​ddbc_bindings.h Declares operation tokens and cancellable-call helpers.
mssql_python/​pybind/​ddbc_bindings.cpp Implements cancellation fences and native recovery support.
mssql_python/​mssql_python.pyi Exposes Cursor.cancel() in public stubs.
mssql_python/​ddbc_bindings.py Imports internal cancellation typing declarations.
mssql_python/​cursor.py Adds cancellation and guards cursor operations.
mssql_python/​connection.py Serializes connection operations through admission state.
mssql_python/​_query_operation.py Implements Python admission and recovery coordination.
mssql_python/​_native_fetch.py Extends fetch eligibility with operation dependencies.
mssql_python/​_ddbc_types.pyi Types internal operation and policy bindings.
mssql_python/​__init__.py Initializes native query admission support.

Review effort: Balanced

Comment thread tests/test_query_cancellation.py Resolved
Comment thread mssql_python/cursor.py Resolved
Comment thread mssql_python/pybind/ddbc_bindings.cpp Resolved
@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

📊 Code Coverage Report

🔥 Diff Coverage

87%


🎯 Overall Coverage

86%


📈 Total Lines Covered: 13343 out of 15481
📁 Project: mssql-python


Diff Coverage

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

  • mssql_python/init.py (100%)
  • mssql_python/_native_fetch.py (97.9%): Missing lines 290
  • mssql_python/_query_operation.py (90.2%): Missing lines 88,95,100,122,129,205,212,215,243-245,259-261,263-265
  • mssql_python/connection.py (100%)
  • mssql_python/cursor.py (98.1%): Missing lines 1280
  • mssql_python/pybind/ddbc_bindings.cpp (83.3%): Missing lines 1741,1748-1750,1757,1759,1770-1774,1797-1799,1812-1817,1821,1856-1865,1879-1880,2524-2526,3902-3905,3961,4262,4437,4489,4782,7273-7275,7283-7284
  • mssql_python/pybind/ddbc_bindings.h (90.5%): Missing lines 488-491
  • mssql_python/pybind/native_fetch.hpp (84.7%): Missing lines 759-761,797,801,808,1081,1096,1105,1108,1112,1118,1124,1132,1292-1297,1338,1340,1343

Summary

  • Total: 775 lines
  • Missing: 96 lines
  • Coverage: 87%

mssql_python/_native_fetch.py

Lines 286-294

  286             or type(query_slot) is not _query_operation.QuerySlot
  287             or type(query_state._native) is not ddbc_bindings._QueryAdmission
  288             or type(query_slot._native) is not ddbc_bindings._QueryOperationSlot
  289         ):
! 290             return None
  291         column_map = data.get("_cached_column_map")
  292         lower_map = data.get("_cached_column_map_lower")
  293         names = data.get("_cached_result_columns")
  294         ddbc_bindings._watch_fetch_dependencies(

mssql_python/_query_operation.py

Lines 84-92

  84         try:
  85             with connection._query_state.lock:
  86                 self.cursor._check_closed()
  87                 if connection.closed or not connection._query_state.reserve(self):
! 88                     raise ProgrammingError(
  89                         "Connection is closed or has an operation in progress", ""
  90                     )
  91                 self.cursor._query_slot.active = self
  92             if self.cancellable:

Lines 91-104

   91                 self.cursor._query_slot.active = self
   92             if self.cancellable:
   93                 self.native = ddbc_bindings._StatementOperation(self.cursor.hstmt)
   94                 if self._cancel_requested:
!  95                     self.native.cancel()
   96             return self
   97         except BaseException:
   98             try:
   99                 if self.native is not None:
! 100                     self.native.finish()
  101             finally:
  102                 with connection._query_state.lock:
  103                     if self.cursor._query_slot.active is self:
  104                         self.cursor._query_slot.active = None

Lines 118-126

  118         try:
  119             try:
  120                 requested = self.native.finish() if self.native is not None else False
  121                 if interrupted:
! 122                     raise OperationalError("Cancellation completion was interrupted", "")
  123                 if requested:
  124                     self.cursor._reset_cursor(checked=True)
  125                     self.cursor.description = None
  126                     self.cursor.rowcount = -1

Lines 125-133

  125                     self.cursor.description = None
  126                     self.cursor.rowcount = -1
  127                     self.cursor.last_executed_stmt = ""
  128                     if self.native is not None and self.native.failed:
! 129                         self._discard()
  130             except BaseException as error:
  131                 # Signals can interrupt GIL reacquisition during finish/free.
  132                 # Never admit new work after incomplete cancellation recovery.
  133                 try:

Lines 201-209

  201     global _NATIVE_QUERY_RUNTIME
  202     # Reentrant finalizers during cold initialization keep the Python protocol.
  203     _NATIVE_QUERY_RUNTIME = False
  204     if not getattr(ddbc_bindings, "_query_policy_available", False):
! 205         return False
  206     try:
  207         from .connection import Connection
  208         from .cursor import Cursor, _NATIVE_FETCH_RUNTIME
  209         from ._native_fetch import _Policy

Lines 208-219

  208         from .cursor import Cursor, _NATIVE_FETCH_RUNTIME
  209         from ._native_fetch import _Policy
  210 
  211         if _NATIVE_FETCH_RUNTIME is None:
! 212             return False
  213         fetch = _NATIVE_FETCH_RUNTIME[2]
  214         if not isinstance(fetch, _Policy):
! 215             raise TypeError("Invalid native fetch policy for query admission")
  216         fetch.classes += (Connection,)
  217         first = len(fetch.functions)
  218         fetch._record_types((Connection,), [])
  219         fetch.dicts += tuple(

Lines 239-249

  239                 "_check_closed",
  240                 "connection",
  241             ),
  242         )
! 243     except BaseException:
! 244         _NATIVE_QUERY_RUNTIME = None
! 245         raise
  246     return _NATIVE_QUERY_RUNTIME
  247 
  248 
  249 def _recover_native_query(

Lines 255-269

  255         operation.connection = cursor.connection
  256         operation.cancellable = True
  257         operation._cancel_requested = True
  258         operation.native = native
! 259     except BaseException:
! 260         try:
! 261             _discard_connection(cursor.connection)
  262         finally:
! 263             cursor._query_slot.active = None
! 264             cursor.connection._query_state.busy = False
! 265         raise
  266     operation._end(failed, interrupted=interrupted)
  267 
  268 
  269 def _discard_connection(connection: Connection) -> None:

mssql_python/cursor.py

Lines 1276-1284

  1276         with self.connection._query_state.lock:
  1277             if self.closed:
  1278                 raise ProgrammingError("Operation cannot be performed: The cursor is closed.", "")
  1279             if self.connection.closed:
! 1280                 raise ProgrammingError("Connection is closed", "")
  1281             operation = self._query_slot.active
  1282         # Never hold the admission lock while SQLCancel or the worker waits.
  1283         if operation is not None:
  1284             operation.cancel()

mssql_python/pybind/ddbc_bindings.cpp

Lines 1737-1745

  1737     : handle(std::move(statement)), previous(activeStatementOperation), cancellable(cancellable) {
  1738     activeStatementOperation = this;
  1739 }
  1740 
! 1741 StatementOperation::~StatementOperation() {
  1742     if (activeStatementOperation == this)
  1743         activeStatementOperation = previous;
  1744 }

Lines 1744-1754

  1744 }
  1745 
  1746 void StatementOperation::restartUnreferenced(bool allowCancellation) {
  1747     // The idle cache is the sole shared owner: no captured request can still
! 1748     // target this token. Do not restart a token retained by a canceller.
! 1749     previous = activeStatementOperation;
! 1750     running.store(false, std::memory_order_relaxed);
  1751     requested.store(false, std::memory_order_relaxed);
  1752     finished.store(false, std::memory_order_relaxed);
  1753     cancelFailed = false;
  1754     cancellable = allowCancellation;

Lines 1753-1763

  1753     cancelFailed = false;
  1754     cancellable = allowCancellation;
  1755     activeStatementOperation = this;
  1756 }
! 1757 
  1758 StatementOperation* StatementOperation::current(SQLHSTMT statement) {
! 1759     auto* operation = activeStatementOperation;
  1760     return operation && operation->cancellable &&
  1761                    !operation->finished.load(std::memory_order_relaxed) && operation->handle &&
  1762                    operation->handle->get() == statement
  1763                ? operation : nullptr;

Lines 1766-1778

  1766 void StatementOperation::bind(SqlHandlePtr statement) {
  1767     // Called only by the owner, between native calls. cancel() may still
  1768     // hold the fence while the owner is reacquiring the GIL.
  1769     py::gil_scoped_release release;
! 1770     std::lock_guard<std::mutex> lock(mutex);
! 1771     if (!finished)
! 1772         handle = std::move(statement);
! 1773 }
! 1774 
  1775 bool StatementOperation::beginCall() {
  1776     if (requested)
  1777         return false;
  1778     running = true;

Lines 1793-1803

  1793         std::lock_guard<std::mutex> lock(mutex);
  1794     }
  1795 }
  1796 
! 1797 void StatementOperation::cancel() {
! 1798     bool unsupported = false;
! 1799     bool unsupportedOperation = false;
  1800     bool failedRequest = false;
  1801     {
  1802         py::gil_scoped_release release;
  1803         std::lock_guard<std::mutex> lock(mutex);

Lines 1808-1825

  1808         } else if (!SQLCancel_ptr) {
  1809             unsupported = true;
  1810         } else {
  1811             requested = true;
! 1812             if (running) {
! 1813                 try {
! 1814                     handle->cancel();
! 1815                 } catch (const std::exception&) {
! 1816                     cancelFailed = true;
! 1817                     failedRequest = true;
  1818                 }
  1819             }
  1820         }
! 1821     }
  1822     if (unsupportedOperation)
  1823         RaiseStatementError("HYC00", "Cancellation is not supported for this operation");
  1824     if (unsupported)
  1825         RaiseStatementError("HYC00", "The selected ODBC provider does not support cancellation");

Lines 1852-1869

  1852     // the GIL, so no canceller can be holding or entering its completion fence.
  1853     finished.store(true, std::memory_order_relaxed);
  1854     if (activeStatementOperation == this)
  1855         activeStatementOperation = previous;
! 1856     return requested.load(std::memory_order_relaxed);
! 1857 }
! 1858 
! 1859 SQLRETURN StatementOperation::checkResult(SQLHSTMT statement, SQLRETURN result, bool attempted) {
! 1860     // endCall already joined cancellation. Later requests can only latch the
! 1861     // logical operation; they cannot issue another SQLCancel against this call.
! 1862     if (!requested)
! 1863         return result;
! 1864     if (attempted && result == SQL_INVALID_HANDLE) {
! 1865         cancelFailed = true;
  1866         RaiseStatementError("HY000", "Invalid statement handle during cancellation");
  1867     }
  1868     ErrorInfo cancellation;
  1869     ErrorInfo failure;

Lines 1875-1884

  1875             // SQLCancel can win just before entry and close the cursor.
  1876             if (error.sqlState == "HY008" || error.sqlState == "HY007" ||
  1877                 error.sqlState == "HY010" || error.sqlState == "24000") {
  1878                 cancellation = std::move(error);
! 1879             } else if (error.sqlState.substr(0, 2) != "01" &&
! 1880                        error.sqlState != "00000") {
  1881                 if (error.sqlState.substr(0, 2) == "08")
  1882                     cancelFailed = true;
  1883                 if (failure.sqlState.empty())
  1884                     failure = std::move(error);

Lines 2520-2530

  2520             rc = ResetParamBindings(*statementHandle, hStmt);
  2521             if (!SQL_SUCCEEDED(rc))
  2522                 return rc;
  2523             SQLWCHAR* queryPtr = reinterpretU16stringAsSqlWChar(query);
! 2524             rc = CancellableCall(hStmt, [&] {
! 2525                 return SQLPrepare_ptr(hStmt, queryPtr, SQL_NTS);
! 2526             });
  2527             if (!SQL_SUCCEEDED(rc)) return rc;
  2528             statementHandle->clearDescribeCache();
  2529             is_stmt_prepared[0] = py::bool_(true);
  2530         } else {

Lines 3898-3909

  3898         case SQL_SMALLINT: return SQL_C_SHORT;
  3899         case SQL_BIGINT: return SQL_C_SBIGINT;
  3900         case SQL_REAL: return SQL_C_FLOAT;
  3901         case SQL_DOUBLE:
! 3902         case SQL_FLOAT: return SQL_C_DOUBLE;
! 3903         default: return 0;
! 3904     }
! 3905 }
  3906 
  3907 static size_t FetchFixedScalarRun(SQLHSTMT statement, StatementOperation* operation,
  3908                                   const ResultMetadata& metadata, size_t first,
  3909                                   size_t count, py::list& row, py::handle messages,

Lines 3957-3965

  3957     for (size_t index = 0; index < read; ++index) {
  3958         const auto& cell = cells[index];
  3959         if (cell.indicator == SQL_NULL_DATA ||
  3960             (index + 1 == read && !SQL_SUCCEEDED(result))) {
! 3961             row.append(py::none());
  3962             continue;
  3963         }
  3964         switch (metadata.columns[first + index].dataType) {
  3965             case SQL_INTEGER: row.append(static_cast<int>(cell.integer)); break;

Lines 4258-4266

  4258                     // VARCHAR(10)).
  4259                     uint64_t fetchBufferSize = columnSize * 4 + 1 /* null-termination */;
  4260                     std::vector<SQLCHAR> dataBuffer(fetchBufferSize);
  4261                     SQLLEN dataLen;
! 4262                     ret = CancellableGetData(hStmt, i, SQL_C_CHAR, dataBuffer.data(), dataBuffer.size(),
  4263                                          &dataLen);
  4264                     CaptureFetchDiagnostics(
  4265                         hStmt, ret, messages,
  4266                         ret == SQL_SUCCESS_WITH_INFO &&

Lines 4433-4441

  4433             }
  4434             case SQL_INTEGER: {
  4435                 SQLINTEGER intValue;
  4436                 SQLLEN indicator = 0;
! 4437                 ret = CancellableGetData(hStmt, i, SQL_C_LONG, &intValue, 0, &indicator);
  4438                 CaptureFetchDiagnostics(hStmt, ret, messages);
  4439                 if (SQL_SUCCEEDED(ret) && indicator != SQL_NULL_DATA) {
  4440                     row.append(static_cast<int>(intValue));
  4441                 } else {

Lines 4485-4493

  4485             case SQL_NUMERIC: {
  4486                 SQLCHAR numericStr[MAX_DIGITS_IN_NUMERIC] = {0};
  4487                 SQLLEN indicator = 0;
  4488 
! 4489                 ret = CancellableGetData(hStmt, i, SQL_C_CHAR, numericStr, sizeof(numericStr),
  4490                                      &indicator);
  4491                 CaptureFetchDiagnostics(hStmt, ret, messages);
  4492 
  4493                 if (SQL_SUCCEEDED(ret) && indicator == SQL_NULL_DATA) {

Lines 4778-4786

  4778             case SQL_GUID: {
  4779                 SQLGUID guidValue;
  4780                 SQLLEN indicator;
  4781                 ret =
! 4782                     CancellableGetData(hStmt, i, SQL_C_GUID, &guidValue, sizeof(guidValue), &indicator);
  4783                 CaptureFetchDiagnostics(hStmt, ret, messages);
  4784 
  4785                 if (SQL_SUCCEEDED(ret) && indicator != SQL_NULL_DATA) {
  4786                     std::vector<char> guid_bytes(16);

Lines 7269-7279

  7269 #ifndef ARCHITECTURE
  7270 #define ARCHITECTURE "win64"  // Default to win64 if not defined during compilation
  7271 #endif
  7272 
! 7273 #if defined(__GNUG__) && !defined(_WIN32)
! 7274 class __attribute__((visibility("hidden"))) ScopedQueryOperation {
! 7275 #else
  7276 class ScopedQueryOperation {
  7277 #endif
  7278     QueryAdmission& admission;
  7279     QueryOperationSlot& slot;

Lines 7279-7288

  7279     QueryOperationSlot& slot;
  7280     py::handle cursor;
  7281     py::handle recover;
  7282     std::shared_ptr<StatementOperation> operation;
! 7283     int exceptions = std::uncaught_exceptions();
! 7284     bool ended = false;
  7285 
  7286   public:
  7287     ScopedQueryOperation(QueryAdmission& admission, QueryOperationSlot& slot,
  7288                          const SqlHandlePtr& handle, py::handle cursor,

mssql_python/pybind/ddbc_bindings.h

  484     if (admitted) {
  485         try {
  486             result = call();
  487         } catch (...) {
! 488             if (operation)
! 489                 operation->endCall();
! 490             throw;
! 491         }
  492         if (operation)
  493             operation->endCall();
  494     }
  495     return result;

mssql_python/pybind/native_fetch.hpp

Lines 755-765

  755     SQLRETURN ret;
  756     auto complete = [&](bool positionCommitted) {
  757         auto row = finish_python(self, mode, values, ret, positionCommitted);
  758         if (mode == Mode::Next && row.is_none()) {
! 759             operationGuard.finish();
! 760             throw py::stop_iteration();
! 761         }
  762         return row;
  763     };
  764     if (mode == Mode::Many && !plan->manyEligible) {
  765         // Keep batch decoding (including malformed-text handling), but complete

Lines 793-805

  793         }
  794         return py::none();
  795     }
  796     if (plan->nextIndex == std::numeric_limits<Py_ssize_t>::max())
! 797         return complete(false);
  798     py::int_ next(plan->nextIndex + 1);
  799     py::int_ rowNumber(plan->nextIndex);
  800     if (!current(self, context, state, *plan, rt))
! 801         return complete(false);
  802     auto counterNames = py::reinterpret_borrow<py::tuple>(rt[5]);
  803     set_counter(*plan, counterNames[0], next);
  804     set_counter(*plan, counterNames[1], rowNumber);
  805     set_counter(*plan, counterNames[2], next);

Lines 804-812

  804     set_counter(*plan, counterNames[1], rowNumber);
  805     set_counter(*plan, counterNames[2], next);
  806     ++plan->nextIndex;
  807     if (!current(self, context, state, *plan, rt))
! 808         return complete(true);
  809 
  810     if (mode == Mode::Value) {
  811         // Decode every column, not just column zero. Eligible plans have no
  812         // converters, UUID processing or customized Row/fetchone behavior.

Lines 1077-1085

  1077 }
  1078 
  1079 inline bool query_policy_eligible(const py::tuple& runtime) {
  1080     if (runtime.size() != 8)
! 1081         throw py::type_error("Invalid native query operation runtime");
  1082     auto* cache = runtime[0].cast<QueryPolicyCache*>();
  1083     const auto epoch = queryPolicyEpoch.load(std::memory_order_relaxed);
  1084     if (cache->epoch != epoch) {
  1085         cache->eligible = runtime[1]().cast<bool>();

Lines 1092-1100

  1092                                      const py::tuple& args, const py::dict& keywords,
  1093                                      const py::tuple& runtime, py::handle fallback,
  1094                                      bool cancellable, bool connectionOperation) {
  1095     if (runtime.size() != 8)
! 1096         throw py::type_error("Invalid native query operation runtime");
  1097     auto original = [&] { return invoke_query_method(receiver, fallback, args, keywords); };
  1098     if (reinterpret_cast<PyObject*>(Py_TYPE(receiver.ptr())) !=
  1099         runtime[connectionOperation ? 3 : 2].ptr())
  1100         return original();

Lines 1101-1116

  1101     if (!query_policy_eligible(runtime))
  1102         return original();
  1103     auto keys = runtime[7].cast<py::tuple>();
  1104     if (keys.size() != 9)
! 1105         throw py::type_error("Invalid native query operation keys");
  1106     for (auto key : keys) {
  1107         if (!PyUnicode_CheckExact(key.ptr()))
! 1108             throw py::type_error("Invalid native query operation key");
  1109     }
  1110     auto data = instance_dict(receiver.ptr());
  1111     if (!data)
! 1112         throw py::error_already_set();
  1113     if (!PyDict_CheckExact(data.ptr()))
  1114         return original();
  1115     auto item = [&](PyObject* dict, size_t key) {
  1116         auto* value = PyDict_GetItemWithError(dict, keys[key].ptr());

Lines 1114-1122

  1114         return original();
  1115     auto item = [&](PyObject* dict, size_t key) {
  1116         auto* value = PyDict_GetItemWithError(dict, keys[key].ptr());
  1117         if (!value && PyErr_Occurred())
! 1118             throw py::error_already_set();
  1119         return value;
  1120     };
  1121     auto shadowed = [&](size_t key) {
  1122         const auto present = PyDict_Contains(data.ptr(), keys[key].ptr());

Lines 1120-1128

  1120     };
  1121     auto shadowed = [&](size_t key) {
  1122         const auto present = PyDict_Contains(data.ptr(), keys[key].ptr());
  1123         if (present < 0)
! 1124             throw py::error_already_set();
  1125         return present != 0;
  1126     };
  1127     PyObject* connection = connectionOperation ? receiver.ptr() : item(data.ptr(), 0);
  1128     if (!connection || reinterpret_cast<PyObject*>(Py_TYPE(connection)) != runtime[3].ptr())

Lines 1128-1136

  1128     if (!connection || reinterpret_cast<PyObject*>(Py_TYPE(connection)) != runtime[3].ptr())
  1129         return original();
  1130     auto connectionDict = connectionOperation ? data : instance_dict(connection);
  1131     if (!connectionDict)
! 1132         throw py::error_already_set();
  1133     if (!PyDict_CheckExact(connectionDict.ptr()))
  1134         return original();
  1135     auto* state = item(connectionDict.ptr(), 1);
  1136     if (!state || reinterpret_cast<PyObject*>(Py_TYPE(state)) != runtime[4].ptr())

Lines 1288-1301

  1288         return;
  1289     }
  1290     observer->query = PyDict_AddWatcher(query_policy_changed);
  1291     if (observer->query < 0) {
! 1292         PyErr_Clear();
! 1293         if (PyErr_WarnEx(PyExc_RuntimeWarning,
! 1294                         "Native query admission acceleration disabled: watcher slots unavailable",
! 1295                         1) < 0)
! 1296             throw py::error_already_set();
! 1297     }
  1298     m.attr("_query_policy_available") = observer->query >= 0;
  1299     // One registration per native-module lifetime. The callbacks retain no
  1300     // watched objects; CPython removes registrations at interpreter teardown.
  1301     m.attr("_fetch_observer") = py::capsule(

Lines 1334-1347

  1334     m.def("_watch_query_policy", [](const py::capsule& capsule, const py::tuple& dicts) {
  1335         auto* observer = static_cast<Observer*>(
  1336             PyCapsule_GetPointer(capsule.ptr(), "mssql_python.native_fetch.Observer"));
  1337         if (!observer)
! 1338             throw py::error_already_set();
  1339         if (observer->query < 0)
! 1340             throw std::runtime_error("Native query policy watcher is unavailable");
  1341         for (auto dict : dicts) {
  1342             if (PyDict_Watch(observer->query, dict.ptr()) < 0)
! 1343                 throw py::error_already_set();
  1344         }
  1345     });
  1346     m.def("_run_query_operation", &run_query_operation);
  1347 }


📋 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.vector_support.hpp: 59.5%
mssql_python.pybind.ddbc_bindings.h: 69.1%
mssql_python.pybind.ddbc_bindings.cpp: 80.2%
mssql_python._native_fetch.py: 80.5%
mssql_python.pybind.row_mapping_cache.hpp: 81.5%
mssql_python.__init__.py: 81.8%
mssql_python.pybind.connection.connection_pool.cpp: 82.5%
mssql_python.pybind.connection.connection.cpp: 84.1%

🔗 Quick Links

⚙️ Build Summary 📋 Coverage Details

View Azure DevOps Build

Browse Full Coverage Report

Preserve pending Arrow reader cleanup after busy admission, release native bound parameter buffers after successful teardown, and cover Python cancellation fallback admission errors.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 14:27

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

Exception-safety gaps can leave a connection stuck busy after interrupted admission and retain cancelled batches’ input-size overrides for subsequent executions.

1 open issue
1 previously missed issue

In code that hasn't changed since last review

Medium severity Clear executemany input sizes when native execution raises

mssql_python/​pybind/​ddbc_bindings.cpp:3363

When cancellation raises from SQLExecuteMany, Cursor.executemany() skips the finally that clears _inputsizes, leaving the cancelled batch's type and size overrides applied to the next execution. Move the native call and diagnostic collection in cursor.py:3056–3070 inside the existing try/finally so overrides are cleared on both returned errors and raised exceptions. Add a regression using setinputsizes(), cancellation, and a subsequent differently typed execution.

3 resolved since last review

Review effort: Balanced

Comment thread mssql_python/_query_operation.py Resolved

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.

One blocking finding: the TVP reentrancy assertion fails on supported Python fallback paths.

Recommendation: Request Changes.

Record fallback reservation ownership atomically, cover reservation and slot publication with cleanup, and preserve competing owners on interrupted entry. Accept both valid reentrant TVP errors and cover forced Python fallback.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 17:19

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

An interruption after reservation but before context entry completes can leave the connection permanently busy, requiring owner-specific cleanup and regression tests for interrupted entry and competing ownership.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Interrupted context entry can leave reservation permanently busy

mssql_python/​_query_operation.py:47

If KeyboardInterrupt occurs after reserve() succeeds but before __enter__ returns, busy remains set and subsequent operations are rejected because Python does not call __exit__ after failed entry. This affects fallback connection operations and cursor/Arrow-reader cleanup even with native acceleration. Add owner-specific exception cleanup, keep the owner token alive through the context lifetime so a rejected entry cannot release another owner's reservation, and cover interrupted entry and competing ownership in regression tests.

1 resolved since last review

Review effort: Balanced

Preserve checked cleanup metadata, fence native vector reads, and integrate buffered procedures with exclusive query admission.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 22:49

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

A critical exception-safety gap can leave a connection permanently busy if entry is interrupted after reservation, requiring attempt-specific cleanup and interrupted-admission tests.

1 open issue

Review effort: Balanced

Comment thread mssql_python/_query_operation.py Resolved

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.

Recommendation: Approve.

Copilot AI balanced review requested due to automatic review settings November 25, 2026 10:21

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

Critical findings show that interrupted connection-state admission can permanently retain a reservation and block subsequent operations, requiring exception-safe owner-specific cleanup and interruption regressions.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 25, 2026 15:36

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

Connection-operation admission lacks owner-specific exception cleanup, so an interruption after reservation can leave the connection permanently busy and block subsequent guarded operations.

No open issues 🎉

Review effort: Balanced

@jahnvi480
Jahnvi Thakkar (jahnvi480) merged commit 605f73c into main Nov 26, 2026
46 of 48 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: large Substantial code update

4 participants