Skip to content

FEAT: add synchronous cursor cancellation - #915

Open
Jahnvi Thakkar (jahnvi480) wants to merge 4 commits into
mainfrom
jahnvi/public-query-cancellation
Open

Jahnvi Thakkar (jahnvi480) wants to merge 4 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.0% 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.971 ms 6.015 ms +21.0%
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.005 ms; py::fetchall::row_wrap +0.001 ms; ddbc::SQLDescribeCol::driver_call +0.000 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Row insertion: py::execute::cpp_call +0.123 ms; ddbc::SQLExecute_wrap +0.089 ms; py::execute::diag_records +0.006 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Executemany inserts: py::executemany::param_type_detection +0.258 ms; ddbc::SqlHandle::free +0.000 ms; ddbc::ConnectionHandle::allocStatementHandle +0.000 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Row-by-row fetching: ddbc::SQLGetData_wrap +0.902 ms; ddbc::FetchSingleRow +0.887 ms; ddbc::NativeCursor::fetch +0.856 ms. Call changes: ddbc::SQLGetData::scalar_group (added, removed, or intermittent).
Transaction commit and rollback: ddbc::SQLExecDirect_wrap +2.145 ms; py::execute::cpp_call +2.054 ms; ddbc::Connection::commit +0.437 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Repeated positional queries: ddbc::NativeCursor::fallback +0.532 ms; ddbc::FetchSingleRow +0.052 ms; ddbc::FetchOne_wrap +0.046 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Repeated named-parameter queries: ddbc::NativeCursor::fallback +0.456 ms; ddbc::SQLExecute_wrap +0.255 ms; py::execute::cpp_call +0.220 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Joined aggregation queries: ddbc::FetchAll_wrap +0.015 ms; ddbc::FetchBatchData +0.015 ms; py::execute::post_execute +0.012 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Large joined-result fetching: py::fetchall::row_wrap +0.147 ms; py::execute::post_execute +0.010 ms; ddbc::SQLDescribeCol_wrap +0.006 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
1.2-million-row fetching: py::fetchall::row_wrap +31.710 ms; ddbc::FetchBatchData::cache_column_metadata +0.146 ms; ddbc::SQLBindColums +0.002 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Common table expression queries: py::execute::cpp_call +0.007 ms; ddbc::SQLExecDirect_wrap +0.006 ms; ddbc::FetchAll_wrap +0.002 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).

Unix / SQL Server 2025

SELECT queries: py::execute::cpp_call +0.009 ms; ddbc::SQLExecDirect_wrap +0.008 ms; py::fetchall::row_wrap +0.002 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Row insertion: py::execute::cpp_call +0.149 ms; ddbc::SQLExecute_wrap +0.113 ms; py::execute::post_execute +0.014 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Executemany inserts: py::executemany::cpp_call +0.951 ms; ddbc::SQLExecuteMany_wrap +0.951 ms; py::executemany::param_type_detection +0.598 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Row-by-row fetching: ddbc::NativeCursor::fetch +0.802 ms; ddbc::FetchSingleRow +0.788 ms; ddbc::SQLGetData_wrap +0.776 ms. Call changes: ddbc::SQLGetData::scalar_group (added, removed, or intermittent).
Transaction commit and rollback: ddbc::Connection::rollback +0.177 ms; ddbc::ConnectionHandle::rollback +0.170 ms; ddbc::SQLExecDirect_wrap +0.133 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Repeated positional queries: ddbc::NativeCursor::fallback +0.469 ms; ddbc::SQLExecute_wrap +0.440 ms; py::execute::cpp_call +0.416 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Repeated named-parameter queries: ddbc::NativeCursor::fallback +0.452 ms; py::execute::cpp_call +0.117 ms; ddbc::SQLExecute_wrap +0.096 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Joined aggregation queries: py::fetchall::row_wrap +0.035 ms; ddbc::FetchBatchData::construct_rows +0.018 ms; ddbc::SQLDescribeCol_wrap +0.005 ms. Call changes: ddbc::NativeCursor::new_operation (added, removed, or intermittent).
Large joined-result fetching: py::execute::post_execute +0.032 ms; ddbc::SQLDescribeCol_wrap +0.001 ms; ddbc::SQLBindColums +0.001 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.722 ms 10.328 ms -4.1% no signal
SELECT queries 1.063 ms 1.242 ms +16.9% no signal
Row insertion 31.139 ms 32.002 ms +2.5% no signal
Executemany inserts 159.471 ms 158.114 ms -0.8% no signal
Fetch-all queries 121.518 ms 119.662 ms -1.8% no signal
Row-by-row fetching 4.971 ms 6.015 ms +21.0% consistent slowdown
Batched row fetching 115.811 ms 117.750 ms +2.0% no signal
Transaction commit and rollback 106.742 ms 112.802 ms +6.0% no signal
Arrow row fetching 89.179 ms 92.677 ms +3.9% no signal
100,000-row insertion 378.540 ms 364.328 ms -4.4% no signal
Row fetching in batches of 100 122.449 ms 123.539 ms +3.5% no signal
Row fetching in batches of 10,000 142.016 ms 128.531 ms -9.5% no signal
Repeated positional queries 32.741 ms 33.652 ms +2.2% no signal
Repeated named-parameter queries 32.875 ms 33.849 ms +2.9% no signal
Legacy 100,000-row insertion 271.892 ms 288.445 ms +5.2% no signal
Insertion with explicit input sizes 431.102 ms 430.606 ms +0.2% no signal
Joined aggregation queries 184.987 ms 182.136 ms -1.6% no signal
Large joined-result fetching 200.095 ms 192.616 ms -3.7% no signal
1.2-million-row fetching 3517.576 ms 3523.458 ms +0.3% no signal
Common table expression queries 5.289 ms 5.456 ms +3.6% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.797 ms 1.181 ms -24.3% no signal
10,000 scalar values / fetchval() (debug disabled) 16.746 ms 18.564 ms +10.9% no signal
10,000 output-converted rows / fetchall() 19.382 ms 19.270 ms -0.6% no signal
10,000 output-converted rows / fetchmany(1000) 23.749 ms 23.881 ms +0.8% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 24.591 ms 27.246 ms +11.2% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 31.884 ms 32.103 ms -0.4% no signal

Unix / SQL Server 2025

Database task Before After Paired change Result
Connection opening 81.120 ms 80.918 ms -0.5% no signal
SELECT queries 1.022 ms 1.284 ms +25.2% no signal
Row insertion 29.753 ms 30.743 ms +3.2% no signal
Executemany inserts 130.912 ms 131.993 ms +1.2% no signal
Fetch-all queries 118.909 ms 118.605 ms -0.3% no signal
Row-by-row fetching 4.785 ms 5.673 ms +19.1% no signal
Batched row fetching 111.045 ms 111.046 ms +1.2% no signal
Transaction commit and rollback 101.921 ms 103.987 ms +2.0% no signal
Arrow row fetching 83.385 ms 88.113 ms +6.2% no signal
100,000-row insertion 341.442 ms 361.852 ms +6.1% no signal
Row fetching in batches of 100 108.427 ms 108.845 ms +0.6% no signal
Row fetching in batches of 10,000 126.191 ms 128.717 ms +3.4% no signal
Repeated positional queries 30.241 ms 31.725 ms +4.1% no signal
Repeated named-parameter queries 30.458 ms 31.830 ms +4.8% no signal
Legacy 100,000-row insertion 250.163 ms 254.167 ms +1.6% no signal
Insertion with explicit input sizes 393.610 ms 409.829 ms +1.0% no signal
Joined aggregation queries 173.935 ms 172.183 ms -1.7% no signal
Large joined-result fetching 204.121 ms 197.115 ms -2.1% no signal
1.2-million-row fetching 3523.676 ms 3569.046 ms +0.7% no signal
Common table expression queries 5.371 ms 5.594 ms +3.2% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.445 ms 1.332 ms -5.9% no signal
10,000 scalar values / fetchval() (debug disabled) 16.546 ms 18.727 ms +14.2% no signal
10,000 output-converted rows / fetchall() 19.061 ms 19.040 ms +1.6% no signal
10,000 output-converted rows / fetchmany(1000) 23.749 ms 24.533 ms +3.6% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 24.586 ms 27.145 ms +9.8% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 32.363 ms 33.081 ms +2.6% no signal
Build and measurement details

ADO build 194786

PR head: 46edfc854023fc68e4f2ccca857b2a3d819ee8ea
Base: 389a318a306dbf880d503037ed8bb2d32a2bd8c3
Measured merge: 3f611f041aff87d68507028825046af44d1aa7df

  • 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

88%


🎯 Overall Coverage

86%


📈 Total Lines Covered: 12855 out of 14861
📁 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 288
  • 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 1218
  • mssql_python/pybind/ddbc_bindings.cpp (85.1%): Missing lines 1716,1723-1725,1732,1734,1745-1749,1772-1774,1787-1792,1796,1831-1840,1854-1855,2498-2500,3620,3873,3896-3898,4174,4349,4401,4694
  • mssql_python/pybind/ddbc_bindings.h (90.5%): Missing lines 484-487
  • 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: 776 lines
  • Missing: 91 lines
  • Coverage: 88%

mssql_python/_native_fetch.py

Lines 284-292

  284             or type(query_slot) is not _query_operation.QuerySlot
  285             or type(query_state._native) is not ddbc_bindings._QueryAdmission
  286             or type(query_slot._native) is not ddbc_bindings._QueryOperationSlot
  287         ):
! 288             return None
  289         column_map = data.get("_cached_column_map")
  290         lower_map = data.get("_cached_column_map_lower")
  291         names = data.get("_cached_result_columns")
  292         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 1214-1222

  1214         with self.connection._query_state.lock:
  1215             if self.closed:
  1216                 raise ProgrammingError("Operation cannot be performed: The cursor is closed.", "")
  1217             if self.connection.closed:
! 1218                 raise ProgrammingError("Connection is closed", "")
  1219             operation = self._query_slot.active
  1220         # Never hold the admission lock while SQLCancel or the worker waits.
  1221         if operation is not None:
  1222             operation.cancel()

mssql_python/pybind/ddbc_bindings.cpp

Lines 1712-1720

  1712     : handle(std::move(statement)), previous(activeStatementOperation), cancellable(cancellable) {
  1713     activeStatementOperation = this;
  1714 }
  1715 
! 1716 StatementOperation::~StatementOperation() {
  1717     if (activeStatementOperation == this)
  1718         activeStatementOperation = previous;
  1719 }

Lines 1719-1729

  1719 }
  1720 
  1721 void StatementOperation::restartUnreferenced(bool allowCancellation) {
  1722     // The idle cache is the sole shared owner: no captured request can still
! 1723     // target this token. Do not restart a token retained by a canceller.
! 1724     previous = activeStatementOperation;
! 1725     running.store(false, std::memory_order_relaxed);
  1726     requested.store(false, std::memory_order_relaxed);
  1727     finished.store(false, std::memory_order_relaxed);
  1728     cancelFailed = false;
  1729     cancellable = allowCancellation;

Lines 1728-1738

  1728     cancelFailed = false;
  1729     cancellable = allowCancellation;
  1730     activeStatementOperation = this;
  1731 }
! 1732 
  1733 StatementOperation* StatementOperation::current(SQLHSTMT statement) {
! 1734     auto* operation = activeStatementOperation;
  1735     return operation && operation->cancellable &&
  1736                    !operation->finished.load(std::memory_order_relaxed) && operation->handle &&
  1737                    operation->handle->get() == statement
  1738                ? operation : nullptr;

Lines 1741-1753

  1741 void StatementOperation::bind(SqlHandlePtr statement) {
  1742     // Called only by the owner, between native calls. cancel() may still
  1743     // hold the fence while the owner is reacquiring the GIL.
  1744     py::gil_scoped_release release;
! 1745     std::lock_guard<std::mutex> lock(mutex);
! 1746     if (!finished)
! 1747         handle = std::move(statement);
! 1748 }
! 1749 
  1750 bool StatementOperation::beginCall() {
  1751     if (requested)
  1752         return false;
  1753     running = true;

Lines 1768-1778

  1768         std::lock_guard<std::mutex> lock(mutex);
  1769     }
  1770 }
  1771 
! 1772 void StatementOperation::cancel() {
! 1773     bool unsupported = false;
! 1774     bool unsupportedOperation = false;
  1775     bool failedRequest = false;
  1776     {
  1777         py::gil_scoped_release release;
  1778         std::lock_guard<std::mutex> lock(mutex);

Lines 1783-1800

  1783         } else if (!SQLCancel_ptr) {
  1784             unsupported = true;
  1785         } else {
  1786             requested = true;
! 1787             if (running) {
! 1788                 try {
! 1789                     handle->cancel();
! 1790                 } catch (const std::exception&) {
! 1791                     cancelFailed = true;
! 1792                     failedRequest = true;
  1793                 }
  1794             }
  1795         }
! 1796     }
  1797     if (unsupportedOperation)
  1798         RaiseStatementError("HYC00", "Cancellation is not supported for this operation");
  1799     if (unsupported)
  1800         RaiseStatementError("HYC00", "The selected ODBC provider does not support cancellation");

Lines 1827-1844

  1827     // the GIL, so no canceller can be holding or entering its completion fence.
  1828     finished.store(true, std::memory_order_relaxed);
  1829     if (activeStatementOperation == this)
  1830         activeStatementOperation = previous;
! 1831     return requested.load(std::memory_order_relaxed);
! 1832 }
! 1833 
! 1834 SQLRETURN StatementOperation::checkResult(SQLHSTMT statement, SQLRETURN result, bool attempted) {
! 1835     // endCall already joined cancellation. Later requests can only latch the
! 1836     // logical operation; they cannot issue another SQLCancel against this call.
! 1837     if (!requested)
! 1838         return result;
! 1839     if (attempted && result == SQL_INVALID_HANDLE) {
! 1840         cancelFailed = true;
  1841         RaiseStatementError("HY000", "Invalid statement handle during cancellation");
  1842     }
  1843     ErrorInfo cancellation;
  1844     ErrorInfo failure;

Lines 1850-1859

  1850             // SQLCancel can win just before entry and close the cursor.
  1851             if (error.sqlState == "HY008" || error.sqlState == "HY007" ||
  1852                 error.sqlState == "HY010" || error.sqlState == "24000") {
  1853                 cancellation = std::move(error);
! 1854             } else if (error.sqlState.substr(0, 2) != "01" &&
! 1855                        error.sqlState != "00000") {
  1856                 if (error.sqlState.substr(0, 2) == "08")
  1857                     cancelFailed = true;
  1858                 if (failure.sqlState.empty())
  1859                     failure = std::move(error);

Lines 2494-2504

  2494             rc = ResetParamBindings(*statementHandle, hStmt);
  2495             if (!SQL_SUCCEEDED(rc))
  2496                 return rc;
  2497             SQLWCHAR* queryPtr = reinterpretU16stringAsSqlWChar(query);
! 2498             rc = CancellableCall(hStmt, [&] {
! 2499                 return SQLPrepare_ptr(hStmt, queryPtr, SQL_NTS);
! 2500             });
  2501             if (!SQL_SUCCEEDED(rc)) return rc;
  2502             statementHandle->clearDescribeCache();
  2503             is_stmt_prepared[0] = py::bool_(true);
  2504         } else {

Lines 3616-3624

  3616 // Non-static so it can be called from inline functions in header
  3617 static SQLRETURN CancellableGetData(SQLHSTMT statement, SQLUSMALLINT column,
  3618                                     SQLSMALLINT type, SQLPOINTER buffer,
  3619                                     SQLLEN length, SQLLEN* indicator) {
! 3620     return CancellableCall(statement, [&] {
  3621         return SQLGetData_ptr(statement, column, type, buffer, length, indicator);
  3622     });
  3623 }

Lines 3869-3877

  3869     {
  3870         // Each column keeps its cancellation fence. A diagnostic-bearing return
  3871         // stops the group before any later call can overwrite its records.
  3872         py::gil_scoped_release release;
! 3873         for (; read < length;) {
  3874             auto& cell = cells[read];
  3875             const auto type = FixedScalarCType(metadata.columns[first + read].dataType);
  3876             result = CancellableCallWithoutGIL(operation, [&] {
  3877                 return SQLGetData_ptr(statement, static_cast<SQLUSMALLINT>(first + read + 1),

Lines 3892-3902

  3892             continue;
  3893         }
  3894         switch (metadata.columns[first + index].dataType) {
  3895             case SQL_INTEGER: row.append(static_cast<int>(cell.integer)); break;
! 3896             case SQL_SMALLINT: row.append(static_cast<int>(cell.smallInteger)); break;
! 3897             case SQL_BIGINT: row.append(static_cast<long long>(cell.big)); break;
! 3898             case SQL_REAL: row.append(cell.real); break;
  3899             default: row.append(cell.floating); break;
  3900         }
  3901     }
  3902     return read;

Lines 4170-4178

  4170                     // VARCHAR(10)).
  4171                     uint64_t fetchBufferSize = columnSize * 4 + 1 /* null-termination */;
  4172                     std::vector<SQLCHAR> dataBuffer(fetchBufferSize);
  4173                     SQLLEN dataLen;
! 4174                     ret = CancellableGetData(hStmt, i, SQL_C_CHAR, dataBuffer.data(), dataBuffer.size(),
  4175                                          &dataLen);
  4176                     CaptureFetchDiagnostics(
  4177                         hStmt, ret, messages,
  4178                         ret == SQL_SUCCESS_WITH_INFO &&

Lines 4345-4353

  4345             }
  4346             case SQL_INTEGER: {
  4347                 SQLINTEGER intValue;
  4348                 SQLLEN indicator = 0;
! 4349                 ret = CancellableGetData(hStmt, i, SQL_C_LONG, &intValue, 0, &indicator);
  4350                 CaptureFetchDiagnostics(hStmt, ret, messages);
  4351                 if (SQL_SUCCEEDED(ret) && indicator != SQL_NULL_DATA) {
  4352                     row.append(static_cast<int>(intValue));
  4353                 } else {

Lines 4397-4405

  4397             case SQL_NUMERIC: {
  4398                 SQLCHAR numericStr[MAX_DIGITS_IN_NUMERIC] = {0};
  4399                 SQLLEN indicator = 0;
  4400 
! 4401                 ret = CancellableGetData(hStmt, i, SQL_C_CHAR, numericStr, sizeof(numericStr),
  4402                                      &indicator);
  4403                 CaptureFetchDiagnostics(hStmt, ret, messages);
  4404 
  4405                 if (SQL_SUCCEEDED(ret) && indicator == SQL_NULL_DATA) {

Lines 4690-4698

  4690             case SQL_GUID: {
  4691                 SQLGUID guidValue;
  4692                 SQLLEN indicator;
  4693                 ret =
! 4694                     CancellableGetData(hStmt, i, SQL_C_GUID, &guidValue, sizeof(guidValue), &indicator);
  4695                 CaptureFetchDiagnostics(hStmt, ret, messages);
  4696 
  4697                 if (SQL_SUCCEEDED(ret) && indicator != SQL_NULL_DATA) {
  4698                     std::vector<char> guid_bytes(16);

mssql_python/pybind/ddbc_bindings.h

  480     if (admitted) {
  481         try {
  482             result = call();
  483         } catch (...) {
! 484             if (operation)
! 485                 operation->endCall();
! 486             throw;
! 487         }
  488         if (operation)
  489             operation->endCall();
  490     }
  491     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.ddbc_bindings.h: 68.4%
mssql_python._native_fetch.py: 80.2%
mssql_python.pybind.row_mapping_cache.hpp: 81.5%
mssql_python.__init__.py: 81.6%
mssql_python.pybind.ddbc_bindings.cpp: 81.8%
mssql_python.pybind.connection.connection_pool.cpp: 82.5%
mssql_python.logging.py: 86.8%
mssql_python.pybind.row_mapping.hpp: 86.8%

🔗 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

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants