Repository navigation
PERF: Reuse cursor-scoped state for row fetching - #858
Conversation
Recover the exact cumulative Source05 native-fetch implementation and its regression coverage against frozen main. Preserve watcher invalidation, ownership, fallback and failure controls without later redesigns. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
PR Performance Report✅ Performance improved2 database tasks consistently improved across 2 measured environments. No consistent slowdowns were detected. 2 IMPROVEMENTS 0 SLOWDOWNS 2/2 ENVIRONMENTS Signal fingerprint
Coverage: 2 of 2 environments completed. Advisory result; does not block merging. Measured timings
Performance diagnosticsPhase times are inclusive diagnostics and must not be added together. They identify where measured time changed, not why it changed. Unix / SQL Server 2022Row-by-row fetching: py::fetchone::cpp_call -4.846 ms; ddbc::FetchOne_wrap -3.948 ms; py::fetchone::row_wrap -0.594 ms. Call changes: ddbc::FetchOne_wrap (1001 -> 1 calls); ddbc::FetchSingleRow (added, removed, or intermittent); ddbc::FetchSingleRow::SQL_UNBIND (added, removed, or intermittent). Unix / SQL Server 2025Row-by-row fetching: py::fetchone::cpp_call -4.569 ms; ddbc::FetchOne_wrap -3.731 ms; py::fetchone::row_wrap -0.581 ms. Call changes: ddbc::FetchOne_wrap (1001 -> 1 calls); ddbc::FetchSingleRow (added, removed, or intermittent); ddbc::FetchSingleRow::SQL_UNBIND (added, removed, or intermittent). All database tasks and timingsUnix / SQL Server 2022
Unix / SQL Server 2025
Build and measurement detailsPR head:
A consistent change requires more than 20% median paired movement, at least 1 ms between the median runtimes, and at least 80% of pairs exceeding the relative threshold in the same direction. A slowdown without enough pair agreement is reported as inconsistent. The displayed change is the median of paired before-and-after ratios. It is not recalculated from the two displayed median runtimes. Both revisions use profiling-enabled builds on the same agent and database, with alternating order and discarded warmups. Results are diagnostic and do not represent production-wheel latency. Raw samples and logs are attached to the ADO run as |
There was a problem hiding this comment.
🔵 Needs a closer look
Native ownership and watcher-based dispatch need human review, with fallback compatibility fixes, cross-platform validation, and performance qualification still outstanding.
2 open issues
What changed in this PR
This PR reduces repeated single-row fetch overhead by reusing cursor-scoped native state while retaining Python fallback paths.
Changes:
- Adds watcher-based native dispatch and garbage-collector-visible ownership for eligible single-row operations.
- Shares the native single-row pipeline, tracks complete metadata, and reuses successful column unbinding.
- Adds parity, mutation, lifetime, operation-count, and isolated failure-control tests.
| File | Description |
|---|---|
| tests/test_single_row_pipeline.py | Tests single-row parity, ownership, and operation counts. |
| tests/test_native_fetch_dispatch.py | Tests dispatch, mutation, lifetime, and failure recovery. |
| mssql_python/pybind/row_factory.hpp | Adds single-row construction and reusable attribute names. |
| mssql_python/pybind/result_metadata.hpp | Distinguishes complete metadata from partial prefixes. |
| mssql_python/pybind/native_fetch.hpp | Implements native state, watchers, dispatch, and fallback. |
| mssql_python/pybind/ddbc_bindings.h | Tracks reusable column-unbinding state. |
| mssql_python/pybind/ddbc_bindings.cpp | Shares single-row fetching and registers native bindings. |
| mssql_python/pybind/CMakeLists.txt | Gates fault controls behind profiling-enabled builds. |
| mssql_python/cursor.py | Adds invalidation, completion helpers, and dispatch installation. |
| mssql_python/_native_fetch.py | Defines eligibility policy and installation rollback. |
Review effort: Balanced
Preserve fallback semantics for dict subclasses and keyword binding, accept CPython 3.15's ordinary dictionary descriptor, and initialize stable policy dependencies before capture. Restore logging state between tests and consolidate duplicate fetch coverage. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
📊 Code Coverage Report
Diff CoverageDiff: main...HEAD, staged and unstaged changes
Summary
mssql_python/_native_fetch.pyLines 102-110 Lines 111-119 Lines 118-126 Lines 154-162 Lines 164-172 Lines 175-183 Lines 245-255 Lines 257-265 Lines 282-306 Lines 306-318 mssql_python/cursor.pyLines 2900-2914 Lines 2919-2927 mssql_python/pybind/ddbc_bindings.cppLines 3454-3462 Lines 3460-3471 Lines 5124-5132 mssql_python/pybind/native_fetch.hppLines 35-47 Lines 276-284 Lines 302-310 Lines 312-320 Lines 324-332 Lines 344-355 Lines 412-420 Lines 423-431 Lines 446-458 Lines 460-468 Lines 494-502 Lines 508-521 Lines 546-554 Lines 569-577 Lines 581-589 Lines 589-597 Lines 614-622 Lines 631-639 Lines 644-652 Lines 659-667 Lines 681-689 Lines 687-698 Lines 704-712 Lines 721-732 Lines 743-755 Lines 754-762 Lines 788-796 Lines 819-850 Lines 871-881 Lines 879-890 Lines 892-902 Lines 908-918 Lines 989-997 Lines 1001-1011 Lines 1046-1054 Lines 1060-1077 Lines 1079-1090 Lines 1101-1109 Lines 1111-1119 Lines 1121-1139 Lines 1144-1169 mssql_python/pybind/row_factory.hppLines 16-24 Lines 22-30 📋 Files Needing Attention📉 Files with overall lowest coverage (click to expand)🔗 Quick Links
|
Do not force eligible fetches through repeated Python-policy preparation when the profiler is enabled. Keep native fetch attribution on the actual execution path, retain all safety and debug-logging guards, and cover both profiler states in the existing operation-count regression. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
Native watcher, GC ownership, and ODBC fetch changes require rebuilt-extension and live SQL Server validation across supported CPython/platform builds that is unavailable here, while current-build performance qualification remains incomplete.
2 open issues
Review effort: Balanced
There was a problem hiding this comment.
🔵 Needs a closer look
Native watcher, GC ownership, and ODBC fetch changes require rebuilt cross-version, live-SQL Server, lifetime, and fault-injection validation unavailable in this source-only review, while release-performance qualification remains outstanding.
No open issues 🎉
3 resolved since last review
Review effort: Balanced
Preserve saved bound fetch methods across consecutive class mutations and decline native admission when mutable dependencies cannot be rearmed. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
Native GC ownership, CPython watcher invalidation, and reentrant fetch behavior require rebuilt-extension and live SQL Server validation across supported interpreters and platforms, which was unavailable here.
No open issues 🎉
Review effort: Balanced
Share the schema eligibility guard between cold and warm fetchmany paths so text retains existing batch conversion semantics. Cover explicit/default calls, cold/warm plans, malformed text, strict-error positioning, and native routing. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
Native watcher dispatch, GC ownership, and GIL/reentry changes require build, live-SQL, cross-version, and lifetime validation unavailable in this review environment, while full performance qualification remains incomplete.
No open issues 🎉
Review effort: Balanced
There was a problem hiding this comment.
Note
Copilot was unable to run its full agentic suite in this review.
Copilot review overview
5 open issues
PyUnicode_Compare(key, internalKey)can set an exception (e.g., on allocation failure). In a… · New The row-wrapping logic now exists in two places: inline infetchone()and in_wrap_fetchone().… · New The row-wrapping logic now exists in two places: inline infetchone()and in_wrap_fetchone().… · New These tests now depend on private logger internals (_cached_level,_is_debug_enabled). That’s… · New These tests now depend on private logger internals (_cached_level,_is_debug_enabled). That’s… · New
Review effort: Lite
There was a problem hiding this comment.
🔵 Needs a closer look
Native ownership, CPython watcher invalidation, and ODBC reentry/reuse changes require native-build, live-SQL, and cross-platform validation unavailable here, while performance qualification remains incomplete.
5 open issues
PyUnicode_Compare(key, internalKey)can set an exception (e.g., on allocation failure). In a… The row-wrapping logic now exists in two places: inline infetchone()and in_wrap_fetchone().… The row-wrapping logic now exists in two places: inline infetchone()and in_wrap_fetchone().… These tests now depend on private logger internals (_cached_level,_is_debug_enabled). That’s… These tests now depend on private logger internals (_cached_level,_is_debug_enabled). That’s…
Review effort: Balanced
Keep watcher key matching allocation-free and exception-neutral. Isolate native connection mocks, serialize shared token accounting, and centralize logger cleanup. Document the intentional inline fallback contract. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
Human assessment is needed to evaluate a subtle fetchmany(False) control-flow discrepancy whose native behavior has not been verified.
No open issues 🎉
5 resolved since last review
PyUnicode_Compare(key, internalKey)can set an exception (e.g., on allocation failure). In a… The row-wrapping logic now exists in two places: inline infetchone()and in_wrap_fetchone().… The row-wrapping logic now exists in two places: inline infetchone()and in_wrap_fetchone().… These tests now depend on private logger internals (_cached_level,_is_debug_enabled). That’s… These tests now depend on private logger internals (_cached_level,_is_debug_enabled). That’s…
Review effort: Balanced
Sumit Sarabhai (sumitmsft)
left a comment
There was a problem hiding this comment.
Reviewed the current diff and directly affected fetch dispatch, invalidation, ownership, decoding, fallback, and regression-test paths. Previously reported concerns are addressed, and no new actionable issues were identified. This source-review approval does not establish release-performance qualification.
Recommendation: Approve
[AB#50320](https://sqlclientdrivers.visualstudio.com/c6d89619-62de-46a0-8b46-70b92a84d85e/_workitems/edit/50320) ### Summary Prepare mssql-python 1.18.0 using the approved customer-facing change inventory since v1.17.0. #### Enhancements - Accept APP/Application Name across synchronous, async and bulk-copy paths; note the async/bulk-copy default application-name change to MSSQL-Python (#884). - Reduce row-to-dictionary, single-row fetch, output-converter batch and fetchmany(1) text-processing overhead (#847, #858, #852, #891). - Cache single-pass pyformat conversion and retain compatible parameter bindings for prepared-statement reuse (#888, #886). - Include mssql-python-rs 0.5.0 improvements: Rust-backed execution, macOS Strict TLS and table-valued parameters in the opt-in Rust ODBC provider (#896). #### Bug Fixes - Avoid unsupported isolation reset when closing pooled Azure Synapse connections (#889). - Respect explicit positive connection timeouts during pooled checkout (#897). - Coordinate Arrow reader cross-thread shutdown/cancellation (#892). - Preserve SQL literal, identifier, comment and escaped-percent behavior during pyformat conversion (#888). - Include Rust-backed timeout, prepared-statement lifetime/cancellation, isolation-change, small-stack connection, streaming-order and SQL_VARIANT decoding fixes (#896). #### Version - Bump mssql_python.__version__ and setup.py from 1.17.0 to 1.18.0. - Replace the previous PyPI highlights with the approved 1.18.0 inventory. - Change exactly three release files; no runtime implementation or dependency-pin changes in this PR. ### Validation - Passed: pinned full-directory Black check, staged Python formatting hook, release-version/highlights/approved-PR inventory checks, and git diff --check. - Not run locally: native rebuild and full integration suite. The isolated project environment lacks runtime/test dependencies and DB_CONNECTION_STRING is unset. No integration-test success is claimed; release qualification remains required. ### Release gates - Keep this PR unmerged until the required PyPI and Conda release/verification gates complete. - Rust dependency verified: mssql-python-rs==0.5.0 was built successfully by ADO build 191702 from stable commit 2f6ab0fa…. Release run 191738 successfully verified/staged and published the wheels through ESRP. All nine wheels are non-yanked on PyPI, and their advertised SHA256 digests match the staging log. There is no wheel-build or publication blocker. The overall release run failed on Guardian findings and dependency-update automation; any required Guardian disposition remains separate and unresolved. - Rust release-source comparison: 0.4.0 at 0c3e3c1436b1234d4e838087ff11140ba68b43a5 to 0.5.0 at 2f6ab0faf2a3a4dbad7dc8f0c4cfe2980eabf41d, verified against version declarations and ADO release sources. --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jahnvi Thakkar <61936179+jahnvi480@users.noreply.github.com>



Work Item / Issue Reference
N/A; the work item above is the sole reference.
Summary
Reuse cursor-scoped native state for eligible one-row fetching while retaining the existing Python fallback behavior.
fetchone(), eligiblefetchmany(1),fetchval(), and iteration on supported GIL-enabled CPython versions. Unsupported interpreters retain the Python methods.SQLGetDatametadata, and reuse successful column unbinding.This is the complete 10-file Source05 delta against
9424705251baf8ded41a8a4968216b1fd9b00929, without later hybrid/converter redesigns or benchmark artifacts. The recovered sources match the measured Source05 archive; no current-base semantic adaptation was needed. There is no public API change.Performance scope
Historical matched Linux diagnostics of these Source05 sources used approximately 42.2% less elapsed time for repeated
fetchone()and 74.1% less for repeatedfetchmany(1)than pinned main. Converter fetching was mixed and 1.1% slower at the paired median; pyodbc remained faster in all retained core-operation pairs. These narrow historical diagnostics are not a new benchmark run or all-API qualification. Converter, pyodbc, and full performance-qualification requirements remain unmet; this PR does not claim merge readiness.