Repository navigation
PERF: Speed up output-converter batching and add CI coverage - #852
Conversation
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 202210,000 output-converted rows / fetchall(): py::fetchall::row_wrap -7.914 ms; ddbc::SQLBindColums -0.000 ms. Unix / SQL Server 202510,000 output-converted rows / fetchall(): py::fetchall::row_wrap -7.958 ms; ddbc::FetchBatchData::SQLFetchScroll_call -0.024 ms; ddbc::SQLDescribeCol_wrap -0.000 ms. 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 dispatch changes require human review, with performance qualification on HOLD and cross-platform validation still limited.
No open issues 🎉
What changed in this PR
Optimizes output-converter fetching across the Python and native driver layers and adds CI benchmark coverage. The change remains draft-only and performance qualification is on HOLD.
Changes:
- Retains owned UTF-16LE bytes and adds guarded native Row construction.
- Adds converter correctness, fallback, mutation, ownership, and dispatch tests.
- Adds two converter-fetch benchmarks, expanding the registry to 24 tasks without changing comparison thresholds.
| File | Description |
|---|---|
| tests/test_output_converter_bytes.py | Tests converter semantics, ownership, and native dispatch. |
| tests/test_036_profiler_ci.py | Tests benchmark boundaries, cleanup, and reporting. |
| mssql_python/row.py | Delegates list-based conversion to native code. |
| mssql_python/pybind/output_converter.hpp | Implements owned text, conversion, and guarded Row construction. |
| mssql_python/pybind/ddbc_bindings.h | Adds deferred text handling to column processors. |
| mssql_python/pybind/ddbc_bindings.cpp | Passes converter maps through fetches and exposes helpers. |
| mssql_python/cursor.py | Integrates native converter paths and fallbacks. |
| eng/profiler_benchmarks/workloads.py | Adds fetchall and fetchmany converter workloads. |
| eng/profiler_benchmarks/report.py | Adds readable benchmark report labels. |
| eng/profiler_benchmarks/README.md | Documents workloads and measurement boundaries. |
Review effort: Balanced
📊 Code Coverage Report
Diff CoverageDiff: main...HEAD, staged and unstaged changes
Summary
mssql_python/pybind/ddbc_bindings.cppLines 3657-3665 3657 py::object text;
3658 if (OutputConverters::enabled(converters, i - 1))
3659 text = OutputConverters::text(textData, textSize);
3660 row.append(text ? text
! 3661 : FetchText::from_utf16_native(textData, textSize));
3662 LOG("SQLGetData: CHAR column %d fetched as WCHAR, "
3663 "length=%lu",
3664 i, (unsigned long)numCharsInData);
3665 } else {Lines 3841-3851 3841 static_cast<Py_ssize_t>(numCharsInData * sizeof(SQLWCHAR));
3842 py::object text;
3843 if (dataType != SQL_SS_VARIANT &&
3844 OutputConverters::enabled(converters, i - 1))
! 3845 text = OutputConverters::text(textData, textSize);
! 3846 row.append(text ? text
! 3847 : FetchText::from_utf16_native(textData, textSize));
3848 LOG("SQLGetData: Appended NVARCHAR string "
3849 "length=%lu for column %d",
3850 (unsigned long)numCharsInData, i);
3851 } else {Lines 4550-4558 4550 SQLRETURN FetchBatchData(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& columnNames,
4551 py::list& rows, SQLUSMALLINT numCols, SQLULEN& numRowsFetched,
4552 const std::vector<SQLUSMALLINT>& lobColumns,
4553 const std::string& charEncoding = "utf-16le", int charCtype = SQL_C_WCHAR,
! 4554 py::handle messages = {}, py::handle converters = {}) {
4555 PERF_TIMER("FetchBatchData");
4556 LOG("FetchBatchData: Fetching data in batches");
4557 SQLRETURN ret;
4558 {mssql_python/pybind/output_converter.hppLines 62-70 62 for (Py_ssize_t i = 0; i < PyList_GET_SIZE(values.ptr()); ++i) {
63 if (raw_text(PyList_GET_ITEM(values.ptr(), i))) {
64 py::object value = original(py::handle(PyList_GET_ITEM(values.ptr(), i)));
65 if (PyList_SetItem(values.ptr(), i, value.release().ptr()) < 0)
! 66 throw py::error_already_set();
67 }
68 }
69 return values;
70 }Lines 108-116 108 if (!replaced && i < PyList_GET_SIZE(result.ptr()) &&
109 raw_text(PyList_GET_ITEM(result.ptr(), i))) {
110 py::object restored = original(py::handle(PyList_GET_ITEM(result.ptr(), i)));
111 if (PyList_SetItem(result.ptr(), i, restored.release().ptr()) < 0)
! 112 throw py::error_already_set();
113 }
114 }
115 for (; i < PyList_GET_SIZE(result.ptr()); ++i) {
116 if (raw_text(PyList_GET_ITEM(result.ptr(), i))) {Lines 115-123 115 for (; i < PyList_GET_SIZE(result.ptr()); ++i) {
116 if (raw_text(PyList_GET_ITEM(result.ptr(), i))) {
117 py::object restored = original(py::handle(PyList_GET_ITEM(result.ptr(), i)));
118 if (PyList_SetItem(result.ptr(), i, restored.release().ptr()) < 0)
! 119 throw py::error_already_set();
120 }
121 }
122 return py::reinterpret_borrow<py::list>(result);
123 }Lines 201-211 201 return false;
202 PyObject* current_apply = PyDict_GetItemWithError(
203 PyModule_GetDict(bindings_.ptr()), apply_name_.ptr());
204 if (!current_apply) {
! 205 if (PyErr_Occurred()) throw py::error_already_set();
! 206 return false;
! 207 }
208 if (current_apply != apply_.ptr()) return false;
209 // Changing function.__code__ does not invalidate the owning type's tag.
210 for (size_t i = 0; i < code_.size(); ++i) {
211 if (code_[i] && PyFunction_GetCode(hooks_[i].ptr()) != code_[i].ptr())Lines 240-254 240 for (Py_ssize_t i = 0; i < PyList_GET_SIZE(rows_data.ptr()); ++i) {
241 py::object values = borrow(PyList_GET_ITEM(rows_data.ptr(), i));
242 PyObject* selected = PyDict_GetItemWithError(cursor_globals.ptr(), row_name_.ptr());
243 if (!selected) {
! 244 if (!PyErr_Occurred()) PyErr_SetString(PyExc_NameError, "name 'Row' is not defined");
! 245 throw py::error_already_set();
! 246 }
247 py::object row_class = borrow(selected);
248 py::object names = cursor.attr("_cached_result_columns");
249 if (!PyList_Check(values.ptr()))
! 250 throw py::type_error("native converter rows must contain lists");
251 result.append(construct(py::reinterpret_borrow<py::list>(values), row_class, converters,
252 column_map, cursor, uuid_indices, lower_map, names));
253 }
254 return result;📋 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: 65.1%
mssql_python.pybind.logger_bridge.hpp: 70.8%
mssql_python._native_fetch.py: 77.4%
mssql_python.pybind.ddbc_bindings.cpp: 80.4%
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
|
There was a problem hiding this comment.
🔵 Needs a closer look
The intertwined native allocation, ownership, and fetch changes require rebuilt-extension, native lifetime, and live SQL Server validation across supported Python/platform combinations, which could not be performed in this review environment.
No open issues 🎉
Review effort: Balanced
Preserve converter and row-to-dictionary profiler workloads and their contract tests; reconcile the combined 25-task registry. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
The intertwined native UTF-16 ownership, Row-constructor bypass, and hook invalidation changes require rebuilt-extension, live SQL Server, and cross-platform validation beyond the available source-only review.
No open issues 🎉
Review effort: Balanced
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
Native ownership, guarded Row construction, and fallback changes require rebuilt-extension and live SQL Server regression validation across supported platforms that this source-only review cannot perform.
No open issues 🎉
Review effort: Balanced
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
Native ownership, constructor-bypass paths, and type-version guards require rebuilt-extension and live SQL Server validation across supported platforms, which this source-only review cannot perform.
No open issues 🎉
Review effort: Balanced
Preserve converter byte forwarding through the new native fetch helpers and retain converter wrapping during fetchmany completion. Count Python dispatch events directly while preserving all native-fetch assertions. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
Native UTF-16 ownership and guarded Row construction require rebuilt-extension and live SQL Server validation across supported platforms, which was unavailable in the read-only review environment.
No open issues 🎉
Review effort: Balanced
There was a problem hiding this comment.
🔵 Needs a closer look
Native ownership and guarded Row-construction changes require rebuilt-extension and live SQL Server regressions to verify callback parity and cross-platform lifetime behavior, which this source-only environment cannot validate.
No open issues 🎉
Review effort: Balanced
Sumit Sarabhai (sumitmsft)
left a comment
There was a problem hiding this comment.
Reviewed the complete diff and directly affected implementation and tests. No actionable issues identified. Recommend approval once remaining CI passes.
[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
Summary
Reduces the overhead of fetching rows with output converters, without changing the public API.
Rowbehavior.fetchall()andfetchmany(1000).Local profiling-OFF benchmarks showed about 33% lower batch-fetch time than pinned main. The
fetchone()improvement target and faster-than-pyodbc target remain unmet.