Skip to content

PERF: Speed up output-converter batching and add CI coverage - #852

Open
Jahnvi Thakkar (jahnvi480) wants to merge 1 commit into
mainfrom
jahnvi/converter-path-speedup
Open

Jahnvi Thakkar (jahnvi480) wants to merge 1 commit into
mainfrom
jahnvi/converter-path-speedup

Conversation

@jahnvi480

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

Copy link
Copy Markdown
Contributor

Work Item / Issue Reference

AB#49494


Summary

Reduces the overhead of fetching rows with output converters, without changing the public API.

  • Passes owned UTF-16LE bytes directly to eligible converter callbacks, avoiding unnecessary conversion to Python strings and back to bytes.
  • Uses guarded native row construction while preserving callback order, NULL handling, converter updates, error fallbacks, and custom Row behavior.
  • Adds focused regression tests and separate 10,000-row CI performance workloads for fetchall() and fetchmany(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.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings October 19, 2026 04:16
@github-actions github-actions Bot added the pr-size: large Substantial code update label Oct 19, 2026
@github-actions

github-actions Bot commented Oct 19, 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
10,000 output-converted rows / fetchall() 30.0% faster 27.7% faster
10,000 output-converted rows / fetchmany(1000) 24.1% faster 30.4% 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 10,000 output-converted rows / fetchall() 27.033 ms 18.976 ms -30.0%
Unix / SQL Server 2022 10,000 output-converted rows / fetchmany(1000) 31.057 ms 22.930 ms -24.1%
Unix / SQL Server 2025 10,000 output-converted rows / fetchall() 27.524 ms 19.841 ms -27.7%
Unix / SQL Server 2025 10,000 output-converted rows / fetchmany(1000) 34.878 ms 23.997 ms -30.4%
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

10,000 output-converted rows / fetchall(): py::fetchall::row_wrap -8.158 ms; py::fetchall::cpp_call -0.112 ms; ddbc::FetchAll_wrap -0.053 ms.
10,000 output-converted rows / fetchmany(1000): py::fetchmany::row_wrap -8.427 ms; ddbc::AppendDiagRecords::SQLGetDiagRec_call -0.004 ms; ddbc::SQLNumResultCols_wrap -0.000 ms.

Unix / SQL Server 2025

10,000 output-converted rows / fetchall(): py::fetchall::row_wrap -7.891 ms.
10,000 output-converted rows / fetchmany(1000): py::fetchmany::row_wrap -10.768 ms; py::fetchmany::cpp_call -0.313 ms; ddbc::FetchMany_wrap -0.302 ms.

All database tasks and timings

Unix / SQL Server 2022

Database task Before After Paired change Result
Connection opening 10.290 ms 10.280 ms +0.3% no signal
SELECT queries 1.028 ms 1.041 ms +0.9% no signal
Row insertion 34.126 ms 34.385 ms +0.4% no signal
Executemany inserts 157.870 ms 158.566 ms -0.0% no signal
Fetch-all queries 118.576 ms 118.278 ms +0.0% no signal
Row-by-row fetching 14.493 ms 14.512 ms +0.8% no signal
Batched row fetching 120.864 ms 116.264 ms -4.9% no signal
Transaction commit and rollback 113.383 ms 113.776 ms +0.5% no signal
Arrow row fetching 91.373 ms 92.437 ms +1.3% no signal
100,000-row insertion 444.107 ms 436.763 ms -0.1% no signal
Row fetching in batches of 100 120.088 ms 120.136 ms -0.0% no signal
Row fetching in batches of 10,000 131.324 ms 127.852 ms -2.6% no signal
Repeated positional queries 33.495 ms 33.594 ms +0.2% no signal
Repeated named-parameter queries 35.747 ms 35.642 ms -0.8% no signal
Legacy 100,000-row insertion 344.680 ms 347.223 ms +0.9% no signal
Insertion with explicit input sizes 480.925 ms 490.785 ms +1.4% no signal
Joined aggregation queries 188.772 ms 177.470 ms -0.5% no signal
Large joined-result fetching 173.380 ms 175.357 ms +1.7% no signal
1.2-million-row fetching 3426.053 ms 3434.676 ms +0.2% no signal
Common table expression queries 5.363 ms 5.308 ms -0.8% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.275 ms 1.331 ms +3.1% no signal
10,000 scalar values / fetchval() (debug disabled) 108.268 ms 108.254 ms +0.8% no signal
10,000 output-converted rows / fetchall() 27.033 ms 18.976 ms -30.0% consistent improvement
10,000 output-converted rows / fetchmany(1000) 31.057 ms 22.930 ms -24.1% consistent improvement

Unix / SQL Server 2025

Database task Before After Paired change Result
Connection opening 98.005 ms 97.921 ms +0.2% no signal
SELECT queries 1.079 ms 1.064 ms -0.5% no signal
Row insertion 34.506 ms 34.071 ms -1.0% no signal
Executemany inserts 156.498 ms 154.967 ms -1.7% no signal
Fetch-all queries 120.969 ms 121.422 ms +0.3% no signal
Row-by-row fetching 14.176 ms 14.924 ms +0.0% no signal
Batched row fetching 116.509 ms 119.945 ms +4.4% no signal
Transaction commit and rollback 114.097 ms 114.712 ms -0.7% no signal
Arrow row fetching 93.858 ms 94.758 ms -0.6% no signal
100,000-row insertion 464.846 ms 432.217 ms -6.0% no signal
Row fetching in batches of 100 121.882 ms 121.624 ms -0.2% no signal
Row fetching in batches of 10,000 141.979 ms 138.569 ms -7.0% no signal
Repeated positional queries 33.900 ms 33.431 ms -1.4% no signal
Repeated named-parameter queries 36.021 ms 36.305 ms +1.1% no signal
Legacy 100,000-row insertion 350.732 ms 345.487 ms -1.5% no signal
Insertion with explicit input sizes 541.730 ms 524.897 ms -0.6% no signal
Joined aggregation queries 160.460 ms 160.820 ms +1.0% no signal
Large joined-result fetching 185.522 ms 184.295 ms +0.4% no signal
1.2-million-row fetching 3555.839 ms 3501.905 ms -0.8% no signal
Common table expression queries 5.139 ms 5.212 ms +2.0% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.471 ms 1.455 ms -1.1% no signal
10,000 scalar values / fetchval() (debug disabled) 106.325 ms 110.732 ms +4.2% no signal
10,000 output-converted rows / fetchall() 27.524 ms 19.841 ms -27.7% consistent improvement
10,000 output-converted rows / fetchmany(1000) 34.878 ms 23.997 ms -30.4% consistent improvement
Build and measurement details

ADO build 183915

PR head: 8cc5076098dbeb84e5861c1cda149049b4309af5
Base: 9424705251baf8ded41a8a4968216b1fd9b00929
Measured merge: 4680b1865ed3c0ca6b1fff0736d1aba794a20f95

  • 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.5015.4; 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 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

@github-actions

Copy link
Copy Markdown

📊 Code Coverage Report

🔥 Diff Coverage

92%


🎯 Overall Coverage

85%


📈 Total Lines Covered: 9701 out of 11360
📁 Project: mssql-python


Diff Coverage

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

  • mssql_python/cursor.py (100%)
  • mssql_python/pybind/ddbc_bindings.cpp (64.0%): Missing lines 3625,3805-3810,4464,6266
  • mssql_python/pybind/ddbc_bindings.h (100%)
  • mssql_python/pybind/output_converter.hpp (94.6%): Missing lines 66,112,119,205-207,244-246,250
  • mssql_python/row.py (100%)

Summary

  • Total: 271 lines
  • Missing: 19 lines
  • Coverage: 92%

mssql_python/pybind/ddbc_bindings.cpp

Lines 3621-3629

  3621                                 py::object text;
  3622                                 if (OutputConverters::enabled(converters, i - 1))
  3623                                     text = OutputConverters::text(textData, textSize);
  3624                                 row.append(text ? text
! 3625                                                 : FetchText::from_utf16_native(textData, textSize));
  3626                                 LOG("SQLGetData: CHAR column %d fetched as WCHAR, "
  3627                                     "length=%lu",
  3628                                     i, (unsigned long)numCharsInData);
  3629                             } else {

Lines 3801-3814

  3801                                 // omits the terminator.
  3802                                 const char* textData =
  3803                                     reinterpret_cast<const char*>(dataBuffer.data());
  3804                                 Py_ssize_t textSize =
! 3805                                     static_cast<Py_ssize_t>(numCharsInData * sizeof(SQLWCHAR));
! 3806                                 py::object text;
! 3807                                 if (dataType != SQL_SS_VARIANT &&
! 3808                                     OutputConverters::enabled(converters, i - 1))
! 3809                                     text = OutputConverters::text(textData, textSize);
! 3810                                 row.append(text ? text
  3811                                                 : FetchText::from_utf16_native(textData, textSize));
  3812                                 LOG("SQLGetData: Appended NVARCHAR string "
  3813                                     "length=%lu for column %d",
  3814                                     (unsigned long)numCharsInData, i);

Lines 4460-4468

  4460 SQLRETURN FetchBatchData(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& columnNames,
  4461                          py::list& rows, SQLUSMALLINT numCols, SQLULEN& numRowsFetched,
  4462                          const std::vector<SQLUSMALLINT>& lobColumns,
  4463                          const std::string& charEncoding = "utf-16le", int charCtype = SQL_C_WCHAR,
! 4464                          py::handle messages = {}, py::handle converters = {}) {
  4465     PERF_TIMER("FetchBatchData");
  4466     LOG("FetchBatchData: Fetching data in batches");
  4467     SQLRETURN ret;
  4468     {

Lines 6262-6270

  6262     fetchStateGuard.configure(&numRowsFetched, fetchSize);
  6263 
  6264     while (ret != SQL_NO_DATA) {
  6265         ret = FetchBatchData(hStmt, buffers, columnNames, rows, numCols, numRowsFetched, lobColumns,
! 6266                              charEncoding, charCtype, messages, converters);
  6267         CheckFetchError(StatementHandle, ret);
  6268         if (!SQL_SUCCEEDED(ret) && ret != SQL_NO_DATA) {
  6269             LOG("FetchAll_wrap: Error when fetching data - SQLRETURN=%d", ret);
  6270             return ret;

mssql_python/pybind/output_converter.hpp

Lines 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.pybind.ddbc_bindings.cpp: 80.1%
mssql_python.pybind.connection.connection_pool.cpp: 82.3%
mssql_python.pybind.connection.connection.cpp: 83.1%
mssql_python.logging.py: 86.2%
mssql_python.pooling.py: 90.1%
mssql_python.pybind.fetch_temporal.hpp: 92.1%

🔗 Quick Links

⚙️ Build Summary 📋 Coverage Details

View Azure DevOps Build

Browse Full Coverage Report

@jahnvi480
Jahnvi Thakkar (jahnvi480) marked this pull request as ready for review October 19, 2026 05:17
@jahnvi480 Jahnvi Thakkar (jahnvi480) changed the title REFACTOR: Speed up output-converter batching and add CI coverage PERF: Speed up output-converter batching and add CI coverage Oct 19, 2026
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants