Skip to content

PERF: Reuse cursor-scoped state for row fetching - #858

Merged
Jahnvi Thakkar (jahnvi480) merged 15 commits into
mainfrom
jahnvi/source05-fetch-pr
Nov 10, 2026
Merged

Jahnvi Thakkar (jahnvi480) merged 15 commits into
mainfrom
jahnvi/source05-fetch-pr

Conversation

@jahnvi480

@jahnvi480 Jahnvi Thakkar (jahnvi480) commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Work Item / Issue Reference

AB#48364

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.

  • Add lazily allocated, GC-visible native State/Context/Plan ownership and direct dispatch for fetchone(), eligible fetchmany(1), fetchval(), and iteration on supported GIL-enabled CPython versions. Unsupported interpreters retain the Python methods.
  • Invalidate plans through public CPython watchers and cursor result transitions. Preserve custom methods/factories, converters, UUID handling, dictionary replacement, reentry, and completion of already-consumed rows without fetching twice.
  • Share the native single-row pipeline, distinguish complete result metadata from partial SQLGetData metadata, and reuse successful column unbinding.
  • Avoid duplicate association validation only after callback-free reuse of an existing State. Retain all five current-plan checks and cold/publication revalidation.
  • Include the existing Source05 dispatch, lifetime, mutation, parity, operation-count, and isolated failure-control regressions. Fault controls require a separate profiling-enabled build and are absent from ordinary builds.

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 repeated fetchmany(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.

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>
Copilot AI balanced review requested due to automatic review settings October 22, 2026 06:28
@github-actions github-actions Bot added the pr-size: large Substantial code update label Oct 22, 2026
@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

PR Performance Report

✅ Performance improved

2 database tasks consistently improved across 2 measured environments. No consistent slowdowns were detected.

2 IMPROVEMENTS 0 SLOWDOWNS 2/2 ENVIRONMENTS

Signal fingerprint

Database task Unix / SQL Server 2022 Unix / SQL Server 2025
Row-by-row fetching 66.1% faster 64.8% faster
10,000 scalar values / fetchval() (debug disabled) 84.5% faster 83.9% faster

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 14.645 ms 4.981 ms -66.1%
Unix / SQL Server 2022 10,000 scalar values / fetchval() (debug disabled) 109.340 ms 16.838 ms -84.5%
Unix / SQL Server 2025 Row-by-row fetching 14.204 ms 5.006 ms -64.8%
Unix / SQL Server 2025 10,000 scalar values / fetchval() (debug disabled) 105.636 ms 16.989 ms -83.9%
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

Row-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).
Batched row fetching: py::fetchmany::row_wrap +3.203 ms; ddbc::FetchBatchData +0.765 ms; ddbc::FetchMany_wrap +0.734 ms. Call changes: ddbc::NativeCursor::fallback (added, removed, or intermittent); ddbc::SQLNumResultCols_wrap (51 -> 1 calls).
Row fetching in batches of 100: ddbc::FetchBatchData +1.082 ms; ddbc::FetchMany_wrap +1.004 ms; ddbc::FetchBatchData::SQLFetchScroll_call +0.984 ms. Call changes: ddbc::NativeCursor::fallback (added, removed, or intermittent); ddbc::SQLNumResultCols_wrap (501 -> 1 calls).
Row fetching in batches of 10,000: py::fetchmany::cpp_call +4.113 ms; ddbc::FetchBatchData::construct_rows +1.586 ms; ddbc::FetchMany_wrap +1.285 ms. Call changes: ddbc::NativeCursor::fallback (added, removed, or intermittent); ddbc::SQLNumResultCols_wrap (6 -> 1 calls).
Repeated positional queries: py::execute::cpp_call +0.392 ms; ddbc::SQLExecute_wrap +0.371 ms; py::execute::diag_records +0.006 ms. Call changes: ddbc::FetchSingleRow (added, removed, or intermittent); ddbc::FetchSingleRow::SQL_UNBIND (added, removed, or intermittent); ddbc::NativeCursor::fallback (added, removed, or intermittent).
Repeated named-parameter queries: py::execute::cpp_call +0.051 ms; ddbc::SQLExecute_wrap +0.051 ms; py::execute::post_execute +0.031 ms. Call changes: ddbc::FetchSingleRow (added, removed, or intermittent); ddbc::FetchSingleRow::SQL_UNBIND (added, removed, or intermittent); ddbc::NativeCursor::fallback (added, removed, or intermittent).
10,000 scalar values / fetchval() (debug disabled): py::fetchone::cpp_call -17.518 ms; ddbc::FetchOne_wrap -10.113 ms; py::fetchone::row_wrap -5.562 ms. Call changes: ddbc::FetchOne_wrap (10001 -> 1 calls); ddbc::FetchSingleRow (added, removed, or intermittent); ddbc::FetchSingleRow::SQL_UNBIND (added, removed, or intermittent).

Unix / SQL Server 2025

Row-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).
Batched row fetching: py::fetchmany::row_wrap +2.697 ms; ddbc::FetchMany_wrap +2.337 ms; ddbc::FetchBatchData +2.069 ms. Call changes: ddbc::NativeCursor::fallback (added, removed, or intermittent); ddbc::SQLNumResultCols_wrap (51 -> 1 calls).
Row fetching in batches of 100: ddbc::FetchBatchData::construct_rows +0.020 ms; ddbc::SQLBindColums +0.010 ms; ddbc::SQLDescribeCol::driver_call +0.000 ms. Call changes: ddbc::NativeCursor::fallback (added, removed, or intermittent); ddbc::SQLNumResultCols_wrap (501 -> 1 calls).
Row fetching in batches of 10,000: ddbc::FetchBatchData::construct_rows +1.437 ms; ddbc::FetchBatchData +0.498 ms. Call changes: ddbc::NativeCursor::fallback (added, removed, or intermittent); ddbc::SQLNumResultCols_wrap (6 -> 1 calls).
Repeated positional queries: py::execute::post_execute +0.112 ms; ddbc::FetchOne_wrap +0.023 ms; ddbc::SQLGetData_wrap +0.023 ms. Call changes: ddbc::FetchSingleRow (added, removed, or intermittent); ddbc::FetchSingleRow::SQL_UNBIND (added, removed, or intermittent); ddbc::NativeCursor::fallback (added, removed, or intermittent).
Repeated named-parameter queries: py::execute::post_execute +0.063 ms; py::execute::param_prep +0.030 ms; ddbc::SQLDescribeCol_wrap +0.004 ms. Call changes: ddbc::FetchSingleRow (added, removed, or intermittent); ddbc::FetchSingleRow::SQL_UNBIND (added, removed, or intermittent); ddbc::NativeCursor::fallback (added, removed, or intermittent).
10,000 scalar values / fetchval() (debug disabled): py::fetchone::cpp_call -16.833 ms; ddbc::FetchOne_wrap -9.664 ms; py::fetchone::row_wrap -5.453 ms. Call changes: ddbc::FetchOne_wrap (10001 -> 1 calls); ddbc::FetchSingleRow (added, removed, or intermittent); ddbc::FetchSingleRow::SQL_UNBIND (added, removed, or intermittent).

All database tasks and timings

Unix / SQL Server 2022

Database task Before After Paired change Result
Connection opening 10.561 ms 10.848 ms +0.8% no signal
SELECT queries 1.041 ms 1.025 ms -1.5% no signal
Row insertion 32.669 ms 32.581 ms -0.3% no signal
Executemany inserts 166.235 ms 163.022 ms -2.1% no signal
Fetch-all queries 123.273 ms 123.424 ms +0.8% no signal
Row-by-row fetching 14.645 ms 4.981 ms -66.1% consistent improvement
Batched row fetching 117.446 ms 118.518 ms +0.9% no signal
Transaction commit and rollback 107.365 ms 107.603 ms -0.5% no signal
Arrow row fetching 90.313 ms 91.405 ms +1.0% no signal
100,000-row insertion 452.512 ms 463.342 ms +2.6% no signal
Row fetching in batches of 100 122.254 ms 122.914 ms -0.9% no signal
Row fetching in batches of 10,000 140.588 ms 133.557 ms +2.1% no signal
Repeated positional queries 32.176 ms 33.720 ms +4.8% no signal
Repeated named-parameter queries 34.886 ms 36.354 ms +4.2% no signal
Legacy 100,000-row insertion 367.288 ms 371.569 ms +1.2% no signal
Insertion with explicit input sizes 503.651 ms 511.685 ms +0.6% no signal
Joined aggregation queries 179.978 ms 178.150 ms -1.0% no signal
Large joined-result fetching 196.211 ms 191.350 ms -3.3% no signal
1.2-million-row fetching 3450.100 ms 3427.930 ms -0.7% no signal
Common table expression queries 5.466 ms 5.597 ms +2.3% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.610 ms 1.397 ms -16.8% no signal
10,000 scalar values / fetchval() (debug disabled) 109.340 ms 16.838 ms -84.5% consistent improvement
10,000 rows x 32 columns / dict(row._mapping) (warm) 32.090 ms 32.390 ms -1.4% no signal

Unix / SQL Server 2025

Database task Before After Paired change Result
Connection opening 96.292 ms 96.834 ms -0.2% no signal
SELECT queries 1.025 ms 0.970 ms -4.5% no signal
Row insertion 32.134 ms 32.317 ms +0.6% no signal
Executemany inserts 150.044 ms 152.050 ms +1.4% no signal
Fetch-all queries 119.309 ms 119.924 ms +0.4% no signal
Row-by-row fetching 14.204 ms 5.006 ms -64.8% consistent improvement
Batched row fetching 114.930 ms 117.189 ms +1.5% no signal
Transaction commit and rollback 106.540 ms 107.206 ms +0.6% no signal
Arrow row fetching 87.260 ms 89.104 ms +2.2% no signal
100,000-row insertion 417.312 ms 416.714 ms -0.6% no signal
Row fetching in batches of 100 121.378 ms 119.089 ms -1.1% no signal
Row fetching in batches of 10,000 134.033 ms 127.750 ms -3.2% no signal
Repeated positional queries 31.483 ms 32.729 ms +4.0% no signal
Repeated named-parameter queries 33.716 ms 35.089 ms +3.4% no signal
Legacy 100,000-row insertion 339.210 ms 340.694 ms +0.6% no signal
Insertion with explicit input sizes 475.089 ms 480.093 ms +1.2% no signal
Joined aggregation queries 157.396 ms 163.449 ms +2.6% no signal
Large joined-result fetching 180.088 ms 175.208 ms -0.0% no signal
1.2-million-row fetching 3407.215 ms 3390.951 ms -0.3% no signal
Common table expression queries 4.922 ms 5.002 ms +1.6% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.918 ms 1.967 ms +3.2% no signal
10,000 scalar values / fetchval() (debug disabled) 105.636 ms 16.989 ms -83.9% consistent improvement
10,000 rows x 32 columns / dict(row._mapping) (warm) 30.232 ms 31.085 ms +2.1% no signal
Build and measurement details

ADO build 190432

PR head: 0d0026b7f32efcebd680a4c0c16be4d389ef4878
Base: 8603956fc7f29776b5deb4cc45aa802d0c2ffa94
Measured merge: dfad4f5b65b22470a45b483131a5c5ab5795609a

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

A consistent change requires more than 20% median paired movement, at least 1 ms between the median runtimes, and at least 80% of pairs exceeding the relative threshold in the same direction. A slowdown without enough pair agreement is reported as inconsistent.

The displayed change is the median of paired before-and-after ratios. It is not recalculated from the two displayed median runtimes.

Both revisions use profiling-enabled builds on the same agent and database, with alternating order and discarded warmups. Results are diagnostic and do not represent production-wheel latency.

Raw samples and logs are attached to the ADO run as profiler-* artifacts.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

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

Comment thread mssql_python/_native_fetch.py Resolved
Comment thread mssql_python/pybind/native_fetch.hpp Resolved
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>
Copilot AI balanced review requested due to automatic review settings October 22, 2026 08:32

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Native ownership and invalidation changes need human review, with an unresolved correctness issue and incomplete cross-platform and performance qualification.

1 open issue
2 resolved since last review

Review effort: Balanced

Comment thread mssql_python/pybind/ddbc_bindings.cpp Resolved
@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

📊 Code Coverage Report

🔥 Diff Coverage

87%


🎯 Overall Coverage

85%


📈 Total Lines Covered: 11393 out of 13345
📁 Project: mssql-python


Diff Coverage

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

  • mssql_python/_native_fetch.py (77.3%): Missing lines 106,115,122,158,168,179,249-251,261,286,289,291-298,301-302,310-317
  • mssql_python/cursor.py (86.0%): Missing lines 2904-2906,2909-2910,2923
  • mssql_python/pybind/ddbc_bindings.cpp (90.2%): Missing lines 3458,3464-3467,5128
  • mssql_python/pybind/native_fetch.hpp (89.4%): Missing lines 39-43,280,306,316,328,348,351,416,427,450,454,464,498,512,517,550,573,585,593,618,635,648,663,685,691,694,708,725,728,747,751,758,792,823,827,830,833,836,839,843,846,875-877,883-886,896-898,912-914,993,1005-1007,1050,1064,1068,1073,1083,1086,1105,1115,1125-1128,1131-1135,1148,1151,1156,1161,1165
  • mssql_python/pybind/row_factory.hpp (92.0%): Missing lines 20,26

Summary

  • Total: 1050 lines
  • Missing: 128 lines
  • Coverage: 87%

mssql_python/_native_fetch.py

Lines 102-110

  102             return None
  103         from mssql_python.connection import Connection
  104 
  105         if type(connection) is not Connection:
! 106             return None
  107         descriptor = vars(Connection).get("__dict__")
  108         if (
  109             Connection.__getattribute__ is not object.__getattribute__
  110             or type(descriptor) is not GetSetDescriptorType

Lines 111-119

  111             # CPython 3.15 shares the ordinary instance-dict descriptor on object.
  112             or descriptor.__objclass__ not in (Connection, object)
  113             or descriptor.__name__ != "__dict__"
  114         ):
! 115             return None
  116         connection_data = object.__getattribute__(connection, "__dict__")
  117         if not ddbc_bindings._watch_fetch_dependencies(
  118             self.observer,
  119             (data, connection_data),

Lines 118-126

  118             self.observer,
  119             (data, connection_data),
  120             self.classes + Connection.__mro__,
  121         ):
! 122             return None
  123         index = data.get("_next_row_index")
  124         if type(index) is not int or index < 1:
  125             return None
  126         if self._conversion_ineligible(data):

Lines 154-162

  154                 for name, value in original.items()
  155             ):
  156                 return None
  157         if self.logger.is_debug_enabled:
! 158             return None
  159         if (
  160             self.row_type.__new__ is not object.__new__
  161             or self.row_type.__setattr__ is not object.__setattr__
  162             or any(

Lines 164-172

  164                 for base in Connection.__mro__
  165                 for name in ("_decoding_generation", "_converters_generation")
  166             )
  167         ):
! 168             return None
  169         if any(name in data for name in vars(self.cursor_type)):
  170             return None
  171         for cached, generation in (
  172             ("_cached_decoding_generation", "_decoding_generation"),

Lines 175-183

  175             if (
  176                 type(data.get(cached)) is not int
  177                 or type(connection_data.get(generation)) is not int
  178             ):
! 179                 return None
  180         if (
  181             data.get("closed") is not False
  182             or data.get("_has_result_set") is not True
  183             or data.get("_skip_increment_for_next_fetch") is not False

Lines 245-255

  245 
  246 
  247 class _InstallRollbackError(RuntimeError):
  248     def __init__(self, installation_error, cleanup_errors):
! 249         self.installation_error = installation_error
! 250         self.cleanup_errors = tuple(cleanup_errors)
! 251         super().__init__(
  252             "Native fetch installation and rollback both failed",
  253             installation_error,
  254             self.cleanup_errors,
  255         )

Lines 257-265

  257 
  258 def install(cursor_type, row_type, namespace):
  259     observer = ddbc_bindings._fetch_observer
  260     if observer is None or not isinstance(getattr(row_type, "_fast_create", None), FunctionType):
! 261         return None
  262     methods = ("fetchone", "fetchmany", "fetchval", "__next__")
  263     fallbacks = tuple(getattr(cursor_type, name) for name in methods)
  264     entries = ddbc_bindings._native_fetch_methods
  265     originals = {name: vars(cursor_type)[name] for name in methods}

Lines 282-306

  282             ("_next_row_index", "_rownumber", "rowcount"),
  283             context,
  284         )
  285         if any(vars(cursor_type).get(name) is not entry for name, entry in zip(methods, entries)):
! 286             raise RuntimeError("Cursor methods changed during native fetch installation")
  287         activate(runtime)
  288         return runtime
! 289     except BaseException as installation_error:
  290         # Unpublished entries can only forward to originals until activation.
! 291         cleanup_errors = []
! 292         for name, entry in zip(methods, entries):
! 293             try:
! 294                 if vars(cursor_type).get(name) is entry:
! 295                     setattr(cursor_type, name, originals[name])
! 296             except BaseException as cleanup_error:
! 297                 cleanup_errors.append((name, cleanup_error))
! 298         survivors = tuple(
  299             name for name, entry in zip(methods, entries) if vars(cursor_type).get(name) is entry
  300         )
! 301         if survivors and not cleanup_errors:
! 302             cleanup_errors.append(
  303                 (
  304                     "descriptors",
  305                     RuntimeError("Native fetch descriptors survived rollback", survivors),
  306                 )

Lines 306-318

  306                 )
  307             )
  308         # Retained descriptors must retain their forwarding functions. A partial
  309         # rollback is terminal, not a context that a later install may reuse.
! 310         terminalize = disable if cleanup_errors else abort
! 311         try:
! 312             terminalize()
! 313         except BaseException as cleanup_error:
! 314             cleanup_errors.append(("context", cleanup_error))
! 315         if cleanup_errors:
! 316             raise _InstallRollbackError(installation_error, cleanup_errors) from installation_error
! 317         raise

mssql_python/cursor.py

Lines 2900-2914

  2900     def _complete_fetchone(self, row_data, ret):
  2901         """Complete an already-consumed fetch, including mutation/error fallback."""
  2902         check_error(_SQL_HANDLE_STMT, self.hstmt, ret)
  2903         if ret == _SQL_NO_DATA:
! 2904             if self._next_row_index == 0 and self.description is not None:
! 2905                 self.rowcount = 0
! 2906             return None
  2907 
  2908         if self._skip_increment_for_next_fetch:
! 2909             self._skip_increment_for_next_fetch = False
! 2910             self._next_row_index += 1
  2911         else:
  2912             self._increment_rownumber()
  2913         self.rowcount = self._next_row_index
  2914         return self._wrap_fetchone(row_data)

Lines 2919-2927

  2919             if not converter_map and not self._uuid_str_indices:
  2920                 return Row._fast_create(
  2921                     row_data, column_map, self, column_map_lower, self._cached_result_columns
  2922                 )
! 2923             return Row(
  2924                 row_data,
  2925                 column_map,
  2926                 cursor=self,
  2927                 converter_map=converter_map,

mssql_python/pybind/ddbc_bindings.cpp

Lines 3454-3462

  3454              dataType == SQL_LONGVARBINARY || dataType == SQL_SS_XML || dataType == SQL_SS_UDT) &&
  3455             (columnSize == 0 || columnSize == SQL_NO_TOTAL || columnSize > SQL_MAX_LOB_SIZE));
  3456 }
  3457 
! 3458 static inline bool CanUseSingleRowForFetchMany(SQLSMALLINT dataType, SQLULEN columnSize) {
  3459     // Bound text conversion has platform/codec-specific fallbacks that GetRowData
  3460     // does not share. Keep that contract even when the requested batch size is one.
  3461     switch (dataType) {
  3462         case SQL_CHAR:

Lines 3460-3471

  3460     // does not share. Keep that contract even when the requested batch size is one.
  3461     switch (dataType) {
  3462         case SQL_CHAR:
  3463         case SQL_VARCHAR:
! 3464         case SQL_LONGVARCHAR:
! 3465         case SQL_WCHAR:
! 3466         case SQL_WVARCHAR:
! 3467         case SQL_WLONGVARCHAR:
  3468             return false;
  3469         default:
  3470             return !IsLobOrVariantColumn(dataType, columnSize);
  3471     }

Lines 5124-5132

  5124     if (singleRowEligible) {
  5125         py::list row;
  5126         ret = FetchSingleRow(StatementHandle, row, charEncoding, wcharEncoding, charCtype, messages);
  5127         if (SQL_SUCCEEDED(ret))
! 5128             rows.append(row);
  5129         return ret;
  5130     }
  5131 
  5132     // Initialized to 0 for LOB path counter; overwritten by ODBC in non-LOB path;

mssql_python/pybind/native_fetch.hpp

Lines 35-47

  35                          PyObject* value) {
  36     if (event != PyDict_EVENT_MODIFIED || dict != internalDict ||
  37         (key != internalKey &&
  38          (!key || !internalKey || !PyUnicode_CheckExact(key) ||
! 39           !PyUnicode_CheckExact(internalKey) || !PyUnicode_IS_ASCII(key) ||
! 40           !PyUnicode_IS_ASCII(internalKey) ||
! 41           PyUnicode_GET_LENGTH(key) != PyUnicode_GET_LENGTH(internalKey) ||
! 42           std::memcmp(PyUnicode_1BYTE_DATA(key), PyUnicode_1BYTE_DATA(internalKey),
! 43                       static_cast<size_t>(PyUnicode_GET_LENGTH(key))) != 0)) ||
  44         value != internalValue)
  45         mutationEpoch.fetch_add(1, std::memory_order_relaxed);
  46     return 0;
  47 }

Lines 276-284

  276     while (PyDict_Next(dict, &position, &key, &value)) {
  277         if (PyUnicode_CheckExact(key) && PyUnicode_GET_LENGTH(key) == length) {
  278             const int comparison = PyUnicode_CompareWithASCIIString(key, name);
  279             if (PyErr_Occurred())
! 280                 throw py::error_already_set();
  281             if (comparison == 0)
  282                 return value;
  283         }
  284     }

Lines 302-310

  302         } else if (PyUnicode_GET_LENGTH(key) ==
  303                    static_cast<Py_ssize_t>(sizeof("_native_fetch_state") - 1)) {
  304             const int comparison = PyUnicode_CompareWithASCIIString(key, "_native_fetch_state");
  305             if (PyErr_Occurred())
! 306                 throw py::error_already_set();
  307             if (comparison == 0)
  308                 result.value = value;
  309         }
  310     }

Lines 312-320

  312 }
  313 
  314 inline bool owned_by(State* state, Context* context, PyObject* receiver) {
  315     if (state->context != reinterpret_cast<PyObject*>(context) || !state->owner)
! 316         return false;
  317 #if PY_VERSION_HEX >= 0x030D0000
  318     PyObject* owner = nullptr;
  319     const int result = PyWeakref_GetRef(state->owner, &owner);
  320     if (result < 0)

Lines 324-332

  324 #else
  325     // The GIL and the call's strong receiver reference cover this borrowed read.
  326     PyObject* owner = PyWeakref_GetObject(state->owner);
  327     if (!owner)
! 328         throw py::error_already_set();
  329     return owner == receiver;
  330 #endif
  331 }

Lines 344-355

  344             reinterpret_cast<void*>(PyObject_GenericSetAttr))
  345         return false;
  346     auto attributes = steal(PyType_GetDict(Py_TYPE(receiver)));
  347     if (!attributes)
! 348         throw py::error_already_set();
  349     if (exact_item(attributes.ptr(), "__dict__") != context->dictDescriptor ||
  350         exact_item(attributes.ptr(), "_native_fetch_state"))
! 351         return false;
  352     auto* handle = exact_item(dict, "hstmt");
  353     auto* index = exact_item(dict, "_next_row_index");
  354     auto* messages = exact_item(dict, "messages");
  355     return exact_item(dict, "closed") == Py_False && handle && handle != Py_None &&

Lines 412-420

  412 #endif
  413         weakOwner = PyWeakref_NewRef(receiver, nullptr);
  414     auto owner = steal(weakOwner);
  415     if (!owner)
! 416         throw py::error_already_set();
  417     PyObject* allocated;
  418 #ifdef MSSQL_NATIVE_FETCH_TEST_FAULTS
  419     if (test_fault(context, 2))
  420         allocated = PyErr_NoMemory();

Lines 423-431

  423         allocated = PyType_GenericAlloc(
  424             reinterpret_cast<PyTypeObject*>(context->stateType), 0);
  425     auto result = steal(allocated);
  426     if (!result)
! 427         throw py::error_already_set();
  428     auto* state = reinterpret_cast<State*>(result.ptr());
  429 #ifdef MSSQL_NATIVE_FETCH_TEST_FAULTS
  430     state->testContext = context;
  431     ++context->faults.statesAllocated;

Lines 446-458

  446     // Allocation can run GC callbacks. Revalidate before a callback-free write,
  447     // retaining the old value so publication cannot release its last reference.
  448     auto now = instance_dict(receiver);
  449     if (!now)
! 450         throw py::error_already_set();
  451     entry = state_entry(dict.ptr());
  452     if (!now.is(dict) || entry.value != old.ptr() ||
  453         !storage_admissible(context, receiver, dict.ptr(), entry))
! 454         return {};
  455     int published;
  456 #ifdef MSSQL_NATIVE_FETCH_TEST_FAULTS
  457     if (test_fault(context, 4)) {
  458         PyErr_NoMemory();

Lines 460-468

  460     } else
  461 #endif
  462         published = PyDict_SetItem(dict.ptr(), context->stateKey, result.ptr());
  463     if (published < 0)
! 464         throw py::error_already_set();
  465 #ifdef MSSQL_NATIVE_FETCH_TEST_FAULTS
  466     ++context->faults.publications;
  467 #endif
  468     return result;

Lines 494-502

  494     auto plan = std::make_shared<Plan>(std::move(dict), epoch);
  495     py::object values = rt[2](py::handle(self), plan->cursorDict);
  496     if (!values.is_none()) {
  497         if (!PyTuple_CheckExact(values.ptr()) || PyTuple_GET_SIZE(values.ptr()) != InputCount)
! 498             throw py::type_error("Invalid native fetch plan");
  499         plan->inputs = std::move(values);
  500         if (!PyDict_CheckExact(plan->at(CursorDict).ptr()) ||
  501             !PyDict_CheckExact(plan->at(ConnectionDict).ptr()) ||
  502             !PyDict_CheckExact(plan->at(ColumnMap).ptr()) ||

Lines 508-521

  508             !PyType_Check(plan->at(ConnectionType).ptr()) ||
  509             !PyLong_CheckExact(plan->at(NextIndex).ptr()) ||
  510             !PyLong_CheckExact(plan->at(ArraySize).ptr()) ||
  511             !PyCallable_Check(plan->at(Factory).ptr()))
! 512             throw py::type_error("Invalid native fetch plan fields");
  513         // current() relies on this watch, not on the Python policy registering it.
  514         auto* observer = static_cast<Observer*>(
  515             PyCapsule_GetPointer(rt[0].ptr(), "mssql_python.native_fetch.Observer"));
  516         if (!observer || PyDict_Watch(observer->dict, plan->cursorDict.ptr()) < 0)
! 517             throw py::error_already_set();
  518         plan->handle = plan->at(Handle).cast<SqlHandlePtr>();
  519         plan->charEncoding = plan->at(CharEncoding).cast<std::string>();
  520         plan->wideEncoding = plan->at(WideEncoding).cast<std::string>();
  521         plan->charCtype = EffectiveCharCtypeForFetch(

Lines 546-554

  546         return false;
  547     auto dict = instance_dict(self);
  548     auto connectionDict = instance_dict(plan.at(Connection).ptr());
  549     if (!dict || !connectionDict)
! 550         throw py::error_already_set();
  551     // fetch() checks the key association before use. The native dictionary watch
  552     // invalidates this epoch on a later state-key change; replacement is checked here.
  553     return dict.is(plan.cursorDict) && connectionDict.is(plan.at(ConnectionDict)) &&
  554            state->dict == dict.ptr() && owned_by(state, context, self) &&

Lines 569-577

  569     internalDict = plan.cursorDict.ptr();
  570     internalKey = name.ptr();
  571     internalValue = value.ptr();
  572     if (PyDict_SetItem(plan.cursorDict.ptr(), name.ptr(), value.ptr()) < 0)
! 573         throw py::error_already_set();
  574 }
  575 
  576 inline py::object finish_python(PyObject* self, Mode mode, const py::list& values,
  577                                  SQLRETURN ret, bool positionCommitted) {

Lines 581-589

  581         py::list rows;
  582         if (SQL_SUCCEEDED(ret))
  583             rows.append(values);
  584         if (positionCommitted)
! 585             return cursor.attr("_wrap_fetchmany")(rows);
  586         return cursor.attr("_complete_fetchmany")(rows, ret);
  587     }
  588     py::object row = positionCommitted ? cursor.attr("_wrap_fetchone")(values)
  589                                       : cursor.attr("_complete_fetchone")(values, ret);

Lines 589-597

  589                                       : cursor.attr("_complete_fetchone")(values, ret);
  590     if (mode == Mode::Value && !row.is_none())
  591         return row[py::int_(0)];
  592     if (mode == Mode::Next && row.is_none())
! 593         throw py::stop_iteration();
  594     return row;
  595 }
  596 
  597 inline bool conversion_ineligible(py::handle data) {

Lines 614-622

  614         else if (length == static_cast<Py_ssize_t>(sizeof("_uuid_str_indices") - 1) &&
  615                  PyUnicode_CompareWithASCIIString(key, "_uuid_str_indices") == 0)
  616             uuidIndices = value;
  617         if (PyErr_Occurred())
! 618             throw py::error_already_set();
  619     }
  620     return !converters || !PyTuple_CheckExact(converters) ||
  621            PyTuple_GET_SIZE(converters) != 0 || uuidIndices != Py_None;
  622 }

Lines 631-639

  631     if (!PyUnicode_CheckExact(key))
  632         return false;
  633     const int comparison = PyUnicode_CompareWithASCIIString(key, "size");
  634     if (PyErr_Occurred())
! 635         throw py::error_already_set();
  636     return comparison == 0;
  637 }
  638 
  639 inline bool explicit_nonunit_size(PyObject* const* args, Py_ssize_t nargs,

Lines 644-652

  644         return false;
  645     int overflow = 0;
  646     const long size = PyLong_AsLongAndOverflow(args[0], &overflow);
  647     if (PyErr_Occurred())
! 648         throw py::error_already_set();
  649     return overflow || size != 1;
  650 }
  651 
  652 inline bool single_size(const Plan& plan, PyObject* const* args, Py_ssize_t nargs,

Lines 659-667

  659         return false;
  660     int overflow = 0;
  661     const long value = PyLong_AsLongAndOverflow(size, &overflow);
  662     if (PyErr_Occurred())
! 663         throw py::error_already_set();
  664     return !overflow && value == 1;
  665 }
  666 
  667 inline py::object fetch(PyObject* self, Context* context, Mode mode,

Lines 681-689

  681         return fallback(self, rt, mode, args, nargs, keywords);
  682 
  683     py::dict dict = instance_dict(object);
  684     if (!dict)
! 685         throw py::error_already_set();
  686     bool needsRevalidation;
  687     auto stateOwner = acquire_state(context, self, dict, needsRevalidation);
  688     auto* state = reinterpret_cast<State*>(stateOwner.ptr());
  689     auto admittedDict = needsRevalidation ? instance_dict(self) : dict;

Lines 687-698

  687     auto stateOwner = acquire_state(context, self, dict, needsRevalidation);
  688     auto* state = reinterpret_cast<State*>(stateOwner.ptr());
  689     auto admittedDict = needsRevalidation ? instance_dict(self) : dict;
  690     if (!admittedDict)
! 691         throw py::error_already_set();
  692     if (!admittedDict.is(dict) ||
  693         (needsRevalidation && state && !associated(state, context, self, dict.ptr())))
! 694         return fallback(self, rt, mode, args, nargs, keywords);
  695     const uint64_t epoch = mutationEpoch.load(std::memory_order_relaxed);
  696     auto plan = state && state->plan ? *state->plan : nullptr;
  697     bool stale = !plan || plan->epoch != epoch || !plan->cursorDict.is(dict);
  698     if (!stale && !plan->inputs.is_none()) {

Lines 704-712

  704     if (stale) {
  705         plan = prepare(self, rt, dict, epoch);
  706         auto preparedDict = instance_dict(self);
  707         if (!preparedDict)
! 708             throw py::error_already_set();
  709         if (state && state->plan && preparedDict.is(dict) &&
  710             associated(state, context, self, dict.ptr())) {
  711             auto old = std::move(*state->plan);
  712             *state->plan = plan;

Lines 721-732

  721             return fallback(self, rt, mode, args, nargs, keywords);
  722         auto metadata = plan->handle->resultMetadata.snapshot();
  723         if (metadata.generation != plan->metadata.generation ||
  724             metadata.metadata != plan->metadata.metadata)
! 725             return fallback(self, rt, mode, args, nargs, keywords);
  726     }
  727     if (mode == Mode::Value && PyList_GET_SIZE(plan->at(Description).ptr()) == 0)
! 728         return fallback(self, rt, mode, args, nargs, keywords);
  729 
  730     PERF_TIMER("NativeCursor::fetch");
  731     py::list values;
  732     SQLRETURN ret = FetchSingleRow(plan->handle, values, plan->charEncoding,

Lines 743-755

  743             throw py::stop_iteration();
  744         return py::none();
  745     }
  746     if (plan->nextIndex == std::numeric_limits<Py_ssize_t>::max())
! 747         return finish_python(self, mode, values, ret, false);
  748     py::int_ next(plan->nextIndex + 1);
  749     py::int_ rowNumber(plan->nextIndex);
  750     if (!current(self, context, state, *plan, rt))
! 751         return finish_python(self, mode, values, ret, false);
  752     auto counterNames = py::reinterpret_borrow<py::tuple>(rt[5]);
  753     set_counter(*plan, counterNames[0], next);
  754     set_counter(*plan, counterNames[1], rowNumber);
  755     set_counter(*plan, counterNames[2], next);

Lines 754-762

  754     set_counter(*plan, counterNames[1], rowNumber);
  755     set_counter(*plan, counterNames[2], next);
  756     ++plan->nextIndex;
  757     if (!current(self, context, state, *plan, rt))
! 758         return finish_python(self, mode, values, ret, true);
  759 
  760     if (mode == Mode::Value) {
  761         // Decode every column, not just column zero. Eligible plans have no
  762         // converters, UUID processing or customized Row/fetchone behavior.

Lines 788-796

  788                                PyObject* keywords) {
  789     try {
  790         auto* context = reinterpret_cast<Context*>(owner);
  791         if (!context->functions)
! 792             throw std::runtime_error("Native fetch context is not initialized");
  793         if (context->runtime && count > 0 &&
  794             PyObject_TypeCheck(args[0], reinterpret_cast<PyTypeObject*>(context->cursorType)) &&
  795             (mode == Mode::Many
  796                  ? valid_many_arguments(count - 1, keywords)

Lines 819-850

  819         auto* context = reinterpret_cast<Context*>(owner);
  820         if (context->disabled)
  821             throw std::runtime_error("Native fetch installation is disabled after incomplete rollback");
  822         if (context->cursorType || context->active)
! 823             throw std::runtime_error("Native fetch context is already installed");
  824         PyObject* cursorType;
  825         PyObject* functions;
  826         if (!PyArg_ParseTuple(args, "OO", &cursorType, &functions))
! 827             return nullptr;
  828         if (!PyType_CheckExact(cursorType) || !PyTuple_CheckExact(functions) ||
  829             PyTuple_GET_SIZE(functions) != 4)
! 830             throw py::type_error("Invalid native fetch installation");
  831         auto bases = steal(PyObject_GetAttrString(cursorType, "__bases__"));
  832         if (!bases)
! 833             throw py::error_already_set();
  834         if (!PyTuple_CheckExact(bases.ptr()) || PyTuple_GET_SIZE(bases.ptr()) != 1 ||
  835             PyTuple_GET_ITEM(bases.ptr(), 0) != reinterpret_cast<PyObject*>(&PyBaseObject_Type))
! 836             throw py::type_error("Native fetch requires a plain Python cursor");
  837         for (Py_ssize_t i = 0; i < 4; ++i) {
  838             if (!PyFunction_Check(PyTuple_GET_ITEM(functions, i)))
! 839                 throw py::type_error("Native fetch fallbacks must be Python functions");
  840         }
  841         auto attributes = steal(PyType_GetDict(reinterpret_cast<PyTypeObject*>(cursorType)));
  842         if (!attributes)
! 843             throw py::error_already_set();
  844         auto* descriptor = exact_item(attributes.ptr(), "__dict__");
  845         if (!descriptor || Py_TYPE(descriptor) != &PyGetSetDescr_Type)
! 846             throw py::type_error("Native fetch requires an ordinary cursor dictionary");
  847         context->cursorType = Py_NewRef(cursorType);
  848         context->functions = Py_NewRef(functions);
  849         context->dictDescriptor = Py_NewRef(descriptor);
  850         Py_RETURN_NONE;

Lines 871-881

  871     for (Py_ssize_t field = 4; field <= 5; ++field) {
  872         auto* names = PyTuple_GET_ITEM(runtime, field);
  873         const Py_ssize_t count = field == 4 ? 5 : 3;
  874         if (!PyTuple_CheckExact(names) || PyTuple_GET_SIZE(names) != count) {
! 875             PyErr_SetString(PyExc_TypeError, "Invalid native fetch field names");
! 876             return nullptr;
! 877         }
  878         for (Py_ssize_t i = 0; i < count; ++i) {
  879             auto* name = PyTuple_GET_ITEM(names, i);
  880             if (!PyUnicode_CheckExact(name) ||
  881                 PyUnicode_CompareWithASCIIString(

Lines 879-890

  879             auto* name = PyTuple_GET_ITEM(names, i);
  880             if (!PyUnicode_CheckExact(name) ||
  881                 PyUnicode_CompareWithASCIIString(
  882                     name, field == 4 ? rowNames[i] : counterNames[i]) != 0) {
! 883                 if (!PyErr_Occurred())
! 884                     PyErr_SetString(PyExc_TypeError, "Invalid native fetch field name");
! 885                 return nullptr;
! 886             }
  887         }
  888     }
  889     context->runtime = Py_NewRef(runtime);
  890     Py_RETURN_NONE;

Lines 892-902

  892 
  893 inline PyObject* abort_install(PyObject* owner, PyObject*) {
  894     auto* context = reinterpret_cast<Context*>(owner);
  895     if (context->disabled || context->runtime || context->active) {
! 896         PyErr_SetString(PyExc_RuntimeError, "Cannot abort an active native fetch context");
! 897         return nullptr;
! 898     }
  899     auto* cursorType = context->cursorType;
  900     auto* functions = context->functions;
  901     auto* descriptor = context->dictDescriptor;
  902     context->cursorType = context->functions = context->dictDescriptor = nullptr;

Lines 908-918

  908 
  909 inline PyObject* disable_install(PyObject* owner, PyObject*) {
  910     auto* context = reinterpret_cast<Context*>(owner);
  911     if (context->runtime || context->active) {
! 912         PyErr_SetString(PyExc_RuntimeError, "Cannot disable an active native fetch context");
! 913         return nullptr;
! 914     }
  915     // Keep every forwarding owner: even descriptors restored on the class may
  916     // have been saved elsewhere. Unpublished entries can never create State.
  917     context->disabled = true;
  918     Py_RETURN_NONE;

Lines 989-997

  989         auto* context = reinterpret_cast<Context*>(owner);
  990         if (reinterpret_cast<PyObject*>(Py_TYPE(receiver)) == context->cursorType) {
  991             auto dict = instance_dict(receiver);
  992             if (!dict)
! 993                 throw py::error_already_set();
  994             auto* value = state_entry(dict.ptr()).value;
  995             if (value && reinterpret_cast<PyObject*>(Py_TYPE(value)) == context->stateType) {
  996                 auto stateOwner = py::reinterpret_borrow<py::object>(value);
  997                 auto* state = reinterpret_cast<State*>(value);

Lines 1001-1011

  1001             }
  1002         }
  1003         Py_RETURN_NONE;
  1004     } catch (...) {
! 1005         py::detail::try_translate_exceptions();
! 1006         return nullptr;
! 1007     }
  1008 }
  1009 
  1010 inline void bind(py::module_& m) {
  1011 #ifdef _MSC_VER

Lines 1046-1054

  1046                                  Py_TPFLAGS_IMMUTABLETYPE,
  1047                              stateSlots};
  1048     auto stateType = steal(PyType_FromSpec(&stateSpec));
  1049     if (!stateType)
! 1050         throw py::error_already_set();
  1051     static PyType_Slot contextSlots[] = {
  1052         {Py_tp_new, reinterpret_cast<void*>(internal_new)},
  1053         {Py_tp_dealloc, reinterpret_cast<void*>(dealloc<Context, context_clear>)},
  1054         {Py_tp_traverse, reinterpret_cast<void*>(context_traverse)},

Lines 1060-1077

  1060                                    Py_TPFLAGS_IMMUTABLETYPE,
  1061                                contextSlots};
  1062     auto contextType = steal(PyType_FromSpec(&contextSpec));
  1063     if (!contextType)
! 1064         throw py::error_already_set();
  1065     auto contextOwner = steal(PyType_GenericAlloc(
  1066         reinterpret_cast<PyTypeObject*>(contextType.ptr()), 0));
  1067     if (!contextOwner)
! 1068         throw py::error_already_set();
  1069     auto* context = reinterpret_cast<Context*>(contextOwner.ptr());
  1070     context->stateType = stateType.release().ptr();
  1071     context->stateKey = PyUnicode_InternFromString("_native_fetch_state");
  1072     if (!context->stateKey)
! 1073         throw py::error_already_set();
  1074     m.attr("_native_fetch_schema") = 2;
  1075 #ifdef MSSQL_NATIVE_FETCH_TEST_FAULTS
  1076     m.attr("_native_fetch_test_fault_schema") = 1;
  1077 #endif

Lines 1079-1090

  1079     py::tuple entries(4);
  1080     for (Py_ssize_t i = 0; i < 4; ++i) {
  1081         py::object function = steal(PyCFunction_NewEx(&methods[i], contextOwner.ptr(), nullptr));
  1082         if (!function)
! 1083             throw py::error_already_set();
  1084         py::object descriptor = steal(PyInstanceMethod_New(function.ptr()));
  1085         if (!descriptor)
! 1086             throw py::error_already_set();
  1087         PyTuple_SET_ITEM(entries.ptr(), i, descriptor.release().ptr());
  1088     }
  1089     m.attr("_native_fetch_methods") = std::move(entries);
  1090     static PyMethodDef controls[] = {

Lines 1101-1109

  1101     };
  1102     for (auto* method = controls; method->ml_name; ++method) {
  1103         auto function = steal(PyCFunction_NewEx(method, contextOwner.ptr(), nullptr));
  1104         if (!function)
! 1105             throw py::error_already_set();
  1106         m.attr(method->ml_name) = std::move(function);
  1107     }
  1108 
  1109     auto observer = std::make_unique<Observer>();

Lines 1111-1119

  1111         PyErr_Clear();
  1112         if (PyErr_WarnEx(PyExc_RuntimeWarning,
  1113                         "Native fetch prototype disabled: CPython watcher slots unavailable",
  1114                         1) < 0)
! 1115             throw py::error_already_set();
  1116         m.attr("_fetch_observer") = py::none();
  1117     };
  1118     observer->dict = PyDict_AddWatcher(dict_changed);
  1119     if (observer->dict < 0) {

Lines 1121-1139

  1121         return;
  1122     }
  1123     observer->type = PyType_AddWatcher(type_changed);
  1124     if (observer->type < 0) {
! 1125         PyDict_ClearWatcher(observer->dict);
! 1126         unavailable();
! 1127         return;
! 1128     }
  1129     observer->function = PyFunction_AddWatcher(function_changed);
  1130     if (observer->function < 0) {
! 1131         PyType_ClearWatcher(observer->type);
! 1132         PyDict_ClearWatcher(observer->dict);
! 1133         unavailable();
! 1134         return;
! 1135     }
  1136     // One registration per native-module lifetime. The callbacks retain no
  1137     // watched objects; CPython removes registrations at interpreter teardown.
  1138     m.attr("_fetch_observer") = py::capsule(
  1139         observer.release(), "mssql_python.native_fetch.Observer", [](void* pointer) {

Lines 1144-1169

  1144                                            const py::tuple& dicts, const py::tuple& types) {
  1145         auto* observer = static_cast<Observer*>(
  1146             PyCapsule_GetPointer(capsule.ptr(), "mssql_python.native_fetch.Observer"));
  1147         if (!observer)
! 1148             throw py::error_already_set();
  1149         for (auto dict : dicts) {
  1150             if (PyDict_Watch(observer->dict, dict.ptr()) < 0)
! 1151                 throw py::error_already_set();
  1152         }
  1153         bool armed = true;
  1154         for (auto type : types) {
  1155             if (!PyType_Check(type.ptr()))
! 1156                 throw py::type_error("Expected a type dependency");
  1157             auto* dependency = reinterpret_cast<PyTypeObject*>(type.ptr());
  1158             if (PyType_GetFlags(dependency) & Py_TPFLAGS_IMMUTABLETYPE)
  1159                 continue;
  1160             if (PyType_Watch(observer->type, type.ptr()) < 0)
! 1161                 throw py::error_already_set();
  1162             // CPython coalesces notifications until a valid tag is assigned again.
  1163             // Rearm without an attribute lookup that could invoke user descriptors.
  1164             if (!PyUnstable_Type_AssignVersionTag(dependency))
! 1165                 armed = false;
  1166         }
  1167         return armed;
  1168     });
  1169 }

mssql_python/pybind/row_factory.hpp

Lines 16-24

  16                                  const py::tuple& attribute_names) {
  17     auto* row_type = reinterpret_cast<PyTypeObject*>(row_class.ptr());
  18     py::object row = steal(row_type->tp_alloc(row_type, 0));
  19     if (!row)
! 20         throw py::error_already_set();
  21     PyObject* fields[] = {values.ptr(), column_map.ptr(), cursor.ptr(),
  22                           column_map_lower.ptr(), column_names.ptr()};
  23     for (Py_ssize_t i = 0; i < 5; ++i) {
  24         if (SetAttribute(row.ptr(), PyTuple_GET_ITEM(attribute_names.ptr(), i),

Lines 22-30

  22                           column_map_lower.ptr(), column_names.ptr()};
  23     for (Py_ssize_t i = 0; i < 5; ++i) {
  24         if (SetAttribute(row.ptr(), PyTuple_GET_ITEM(attribute_names.ptr(), i),
  25                          fields[i]) < 0)
! 26             throw py::error_already_set();
  27     }
  28     return row;
  29 }


📋 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: 62.6%
mssql_python.pybind.logger_bridge.hpp: 70.8%
mssql_python._native_fetch.py: 77.4%
mssql_python.pybind.ddbc_bindings.cpp: 80.3%
mssql_python.pybind.connection.connection_pool.cpp: 81.3%
mssql_python.pybind.row_mapping_cache.hpp: 81.5%
mssql_python.pybind.connection.connection.cpp: 82.5%
mssql_python.logging.py: 86.2%

🔗 Quick Links

⚙️ Build Summary 📋 Coverage Details

View Azure DevOps Build

Browse Full Coverage Report

Copilot AI balanced review requested due to automatic review settings October 22, 2026 08:53

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Native ownership and watcher-based dispatch need final human review, with cross-platform, sanitizer, and full performance qualification still outstanding.

1 open issue

Review effort: Balanced

@jahnvi480
Jahnvi Thakkar (jahnvi480) marked this pull request as draft October 28, 2026 05:02
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>
Copilot AI balanced review requested due to automatic review settings October 28, 2026 05:57

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

Human assessment is needed because a reproduced type-watcher notification gap may allow cached fetch plans to bypass cursor overrides, while the full driver impact remains unverified.

1 open issue

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings October 28, 2026 08:44

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

Active issues can turn nullable DECIMAL/NUMERIC results into NaN instead of None and invoke state or policy hooks before malformed fetchmany calls receive the expected TypeError.

2 open issues

Review effort: Balanced

Comment thread mssql_python/pybind/native_fetch.hpp Resolved
@jahnvi480
Jahnvi Thakkar (jahnvi480) marked this pull request as ready for review October 28, 2026 09:14
Copilot AI balanced review requested due to automatic review settings November 4, 2026 06:17

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Native 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

Copilot AI balanced review requested due to automatic review settings November 5, 2026 11:00

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Native 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>
Copilot AI balanced review requested due to automatic review settings November 6, 2026 06:46

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Native 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

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Native 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

Copilot AI balanced review requested due to automatic review settings November 8, 2026 09:12

Copilot AI left a comment

Copy link
Copy Markdown
Contributor
Comment thread mssql_python/pybind/native_fetch.hpp Resolved
Comment thread mssql_python/cursor.py Resolved
Comment thread mssql_python/cursor.py Resolved
Copilot AI balanced review requested due to automatic review settings November 9, 2026 05:39

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.

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>
Copilot AI balanced review requested due to automatic review settings November 9, 2026 08:28

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed the 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

@jahnvi480
Jahnvi Thakkar (jahnvi480) merged commit d66b620 into main Nov 10, 2026
38 checks passed
Jahnvi Thakkar (jahnvi480) added a commit that referenced this pull request Nov 18, 2026
[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>
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