You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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 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.
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>
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.
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.
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.
84try:
85withconnection._query_state.lock:
86self.cursor._check_closed()
87ifconnection.closedornotconnection._query_state.reserve(self):
! 88raiseProgrammingError(
89"Connection is closed or has an operation in progress", ""90 )
91self.cursor._query_slot.active=self92ifself.cancellable:
125self.cursor.description=None126self.cursor.rowcount=-1127self.cursor.last_executed_stmt=""128ifself.nativeisnotNoneandself.native.failed:
! 129self._discard()
130exceptBaseExceptionaserror:
131# Signals can interrupt GIL reacquisition during finish/free.132# Never admit new work after incomplete cancellation recovery.133try:
Lines 201-209
201global_NATIVE_QUERY_RUNTIME202# Reentrant finalizers during cold initialization keep the Python protocol.203_NATIVE_QUERY_RUNTIME=False204ifnotgetattr(ddbc_bindings, "_query_policy_available", False):
! 205returnFalse206try:
207from .connectionimportConnection208from .cursorimportCursor, _NATIVE_FETCH_RUNTIME209from ._native_fetchimport_Policy
1214withself.connection._query_state.lock:
1215ifself.closed:
1216raiseProgrammingError("Operation cannot be performed: The cursor is closed.", "")
1217ifself.connection.closed:
! 1218raiseProgrammingError("Connection is closed", "")
1219operation=self._query_slot.active1220# Never hold the admission lock while SQLCancel or the worker waits.1221ifoperationisnotNone:
1222operation.cancel()
1719 }
17201721voidStatementOperation::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;
1741voidStatementOperation::bind(SqlHandlePtr statement) {
1742// Called only by the owner, between native calls. cancel() may still1743// hold the fence while the owner is reacquiring the GIL.1744 py::gil_scoped_release release;
! 1745 std::lock_guard<std::mutex> lock(mutex);
! 1746if (!finished)
! 1747 handle = std::move(statement);
! 1748 }
! 17491750boolStatementOperation::beginCall() {
1751if (requested)
1752returnfalse;
1753 running = true;
3616// Non-static so it can be called from inline functions in header3617staticSQLRETURNCancellableGetData(SQLHSTMT statement, SQLUSMALLINT column,
3618SQLSMALLINT type, SQLPOINTER buffer,
3619SQLLEN length, SQLLEN* indicator) {
! 3620returnCancellableCall(statement, [&] {
3621returnSQLGetData_ptr(statement, column, type, buffer, length, indicator);
3622 });
3623 }
Lines 3869-3877
3869 {
3870// Each column keeps its cancellation fence. A diagnostic-bearing return3871// stops the group before any later call can overwrite its records.3872 py::gil_scoped_release release;
! 3873for (; read < length;) {
3874auto& cell = cells[read];
3875constauto type = FixedScalarCType(metadata.columns[first + read].dataType);
3876 result = CancellableCallWithoutGIL(operation, [&] {
3877returnSQLGetData_ptr(statement, static_cast<SQLUSMALLINT>(first + read + 1),
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.
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.
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>
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
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Work Item / Issue Reference
Summary
Second dependent layer, targeting
jahnvi/cancellation-native-foundations: expose synchronousCursor.cancel()with operation identity, admission/completion fences, checked recovery, and fail-closed connection retirement. This is a draft for review, not shipping-ready.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.finishUncapturedcondition; no speculative ownership-count optimization is included.Extracted and three-way integrated source snapshot
88f01a77a668d6a3f8b45ccb2b501854a1d6cee2(original source base52f30011b0b0229544cc50a8ef9f8ca0fb3d0e65) onto verified parent tip42e0bd339c1a74de8f850a70dd1ee433a2869120. 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.
pythonbelow denotes the approved development-venv interpreter. T: maps only this worktree; no other checkout or extension was modified.build.bat x64: passed withENABLE_PROFILING=ONandMSSQL_ARROW_TEST_INTERPOSITION=ON. Configured the separate fault build withcmake -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 withcmake -S T:\mssql_python\pybind -B T:\mssql_python\pybind\build\x64\py313 -DBUILD_NATIVE_POOL_TESTS=ONandcmake --build T:\mssql_python\pybind\build\x64\py313 --config Release --target pool_sanitation_tests --parallel 2 -- /verbosity:minimal: both passed.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 withMSSQL_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.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.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=OFFandcmake --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.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.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-pushandgit 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.