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 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 GetSetDescriptorTypeLines 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 FalseLines 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 raisemssql_python/cursor.pyLines 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.cppLines 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.hppLines 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_VERLines 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 #endifLines 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.hppLines 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
|
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.