Skip to content

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

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

Jahnvi Thakkar (jahnvi480) wants to merge 2 commits 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() 28.8% faster 27.7% faster
10,000 output-converted rows / fetchmany(1000) 24.0% faster 23.5% 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() 26.752 ms 19.302 ms -28.8%
Unix / SQL Server 2022 10,000 output-converted rows / fetchmany(1000) 30.211 ms 22.982 ms -24.0%
Unix / SQL Server 2025 10,000 output-converted rows / fetchall() 27.686 ms 20.006 ms -27.7%
Unix / SQL Server 2025 10,000 output-converted rows / fetchmany(1000) 31.400 ms 24.022 ms -23.5%
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 -7.447 ms; ddbc::FetchBatchData::SQLFetchScroll_call -0.258 ms; py::fetchall::cpp_call -0.182 ms.
10,000 output-converted rows / fetchmany(1000): py::fetchmany::row_wrap -7.574 ms; ddbc::SQLNumResultCols_wrap -0.001 ms; ddbc::SQLDescribeCol::driver_call -0.000 ms.

Unix / SQL Server 2025

10,000 output-converted rows / fetchall(): py::fetchall::row_wrap -7.737 ms; ddbc::FetchBatchData::SQLFetchScroll_call -0.208 ms; py::fetchall::cpp_call -0.201 ms.
10,000 output-converted rows / fetchmany(1000): py::fetchmany::row_wrap -7.759 ms; ddbc::SQLDescribeCol::driver_call -0.000 ms.

All database tasks and timings

Unix / SQL Server 2022

Database task Before After Paired change Result
Connection opening 10.224 ms 10.297 ms -0.2% no signal
SELECT queries 1.071 ms 0.994 ms -3.6% no signal
Row insertion 32.549 ms 32.288 ms -0.9% no signal
Executemany inserts 156.696 ms 158.017 ms -0.0% no signal
Fetch-all queries 120.127 ms 119.856 ms -0.4% no signal
Row-by-row fetching 14.146 ms 14.495 ms +2.5% no signal
Batched row fetching 115.841 ms 115.623 ms +0.1% no signal
Transaction commit and rollback 106.335 ms 107.139 ms +0.7% no signal
Arrow row fetching 89.383 ms 90.182 ms +2.6% no signal
100,000-row insertion 431.419 ms 431.010 ms +0.9% no signal
Row fetching in batches of 100 119.138 ms 121.497 ms +2.0% no signal
Row fetching in batches of 10,000 136.579 ms 125.098 ms -2.9% no signal
Repeated positional queries 32.380 ms 31.608 ms -2.1% no signal
Repeated named-parameter queries 34.623 ms 33.724 ms -1.7% no signal
Legacy 100,000-row insertion 345.398 ms 349.060 ms +0.6% no signal
Insertion with explicit input sizes 478.543 ms 480.114 ms -0.0% no signal
Joined aggregation queries 177.351 ms 178.354 ms +0.4% no signal
Large joined-result fetching 184.025 ms 186.133 ms +0.7% no signal
1.2-million-row fetching 3384.438 ms 3429.092 ms +1.3% no signal
Common table expression queries 5.416 ms 5.304 ms -2.5% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.524 ms 1.331 ms -2.1% no signal
10,000 scalar values / fetchval() (debug disabled) 106.811 ms 107.574 ms +1.6% no signal
10,000 output-converted rows / fetchall() 26.752 ms 19.302 ms -28.8% consistent improvement
10,000 output-converted rows / fetchmany(1000) 30.211 ms 22.982 ms -24.0% consistent improvement

Unix / SQL Server 2025

Database task Before After Paired change Result
Connection opening 96.612 ms 96.032 ms -0.8% no signal
SELECT queries 1.007 ms 1.019 ms -0.1% no signal
Row insertion 32.796 ms 32.508 ms -0.3% no signal
Executemany inserts 153.457 ms 152.121 ms -0.4% no signal
Fetch-all queries 121.638 ms 120.832 ms -0.7% no signal
Row-by-row fetching 14.586 ms 14.490 ms -0.5% no signal
Batched row fetching 117.859 ms 117.630 ms -0.4% no signal
Transaction commit and rollback 107.518 ms 107.961 ms +0.4% no signal
Arrow row fetching 89.734 ms 91.390 ms +2.8% no signal
100,000-row insertion 425.334 ms 426.041 ms -1.6% no signal
Row fetching in batches of 100 123.610 ms 122.207 ms -0.2% no signal
Row fetching in batches of 10,000 126.433 ms 131.624 ms +1.9% no signal
Repeated positional queries 32.087 ms 31.725 ms -1.1% no signal
Repeated named-parameter queries 34.103 ms 34.087 ms +1.1% no signal
Legacy 100,000-row insertion 337.394 ms 338.075 ms +0.2% no signal
Insertion with explicit input sizes 471.994 ms 470.197 ms -1.5% no signal
Joined aggregation queries 161.029 ms 160.082 ms -0.8% no signal
Large joined-result fetching 184.814 ms 187.691 ms +2.2% no signal
1.2-million-row fetching 3417.496 ms 3446.414 ms +1.2% no signal
Common table expression queries 4.990 ms 4.962 ms -1.4% no signal
256 KiB VARCHAR(MAX) / fetchall() 2.079 ms 2.088 ms -0.7% no signal
10,000 scalar values / fetchval() (debug disabled) 107.178 ms 109.655 ms +2.1% no signal
10,000 output-converted rows / fetchall() 27.686 ms 20.006 ms -27.7% consistent improvement
10,000 output-converted rows / fetchmany(1000) 31.400 ms 24.022 ms -23.5% consistent improvement
Build and measurement details

ADO build 189059

PR head: 0472671f6d456fdad81ade2c22f40138303ccf40
Base: 5fd233198989a000143b32718adf2d9d2a103b13
Measured merge: db1c37bdb8199b86be01e1f625ade8a9dede5b68

  • 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 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

github-actions Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

📊 Code Coverage Report

🔥 Diff Coverage

93%


🎯 Overall Coverage

85%


📈 Total Lines Covered: 9920 out of 11628
📁 Project: mssql-python


Diff Coverage

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

  • mssql_python/cursor.py (100%)
  • mssql_python/pybind/ddbc_bindings.cpp (68.0%): Missing lines 3646,3826-3831,4485
  • 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: 18 lines
  • Coverage: 93%

mssql_python/pybind/ddbc_bindings.cpp

Lines 3642-3650

  3642                                 py::object text;
  3643                                 if (OutputConverters::enabled(converters, i - 1))
  3644                                     text = OutputConverters::text(textData, textSize);
  3645                                 row.append(text ? text
! 3646                                                 : FetchText::from_utf16_native(textData, textSize));
  3647                                 LOG("SQLGetData: CHAR column %d fetched as WCHAR, "
  3648                                     "length=%lu",
  3649                                     i, (unsigned long)numCharsInData);
  3650                             } else {

Lines 3822-3835

  3822                                 // omits the terminator.
  3823                                 const char* textData =
  3824                                     reinterpret_cast<const char*>(dataBuffer.data());
  3825                                 Py_ssize_t textSize =
! 3826                                     static_cast<Py_ssize_t>(numCharsInData * sizeof(SQLWCHAR));
! 3827                                 py::object text;
! 3828                                 if (dataType != SQL_SS_VARIANT &&
! 3829                                     OutputConverters::enabled(converters, i - 1))
! 3830                                     text = OutputConverters::text(textData, textSize);
! 3831                                 row.append(text ? text
  3832                                                 : FetchText::from_utf16_native(textData, textSize));
  3833                                 LOG("SQLGetData: Appended NVARCHAR string "
  3834                                     "length=%lu for column %d",
  3835                                     (unsigned long)numCharsInData, i);

Lines 4481-4489

  4481 SQLRETURN FetchBatchData(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& columnNames,
  4482                          py::list& rows, SQLUSMALLINT numCols, SQLULEN& numRowsFetched,
  4483                          const std::vector<SQLUSMALLINT>& lobColumns,
  4484                          const std::string& charEncoding = "utf-16le", int charCtype = SQL_C_WCHAR,
! 4485                          py::handle messages = {}, py::handle converters = {}) {
  4486     PERF_TIMER("FetchBatchData");
  4487     LOG("FetchBatchData: Fetching data in batches");
  4488     SQLRETURN ret;
  4489     {

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: 81.3%
mssql_python.pybind.connection.connection.cpp: 82.5%
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
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

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

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