Skip to content

FIX: Preserve executemany values with lossless batch inference - #907

Open
Jahnvi Thakkar (jahnvi480) wants to merge 10 commits into
mainfrom
jahnvi/executemany-unicode-binding
Open

Jahnvi Thakkar (jahnvi480) wants to merge 10 commits into
mainfrom
jahnvi/executemany-unicode-binding

Conversation

@jahnvi480

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

Copy link
Copy Markdown
Contributor

Work Item / Issue Reference

AB#50465

N/A — maintainer ADO reference above.


Summary

Fix lossless executemany inference across Unicode, Decimal, and mixed-type batches. Compute batch text metadata natively, preserve explicit overrides and rowcounts, and retain embedded/trailing NULs during binding and retrieval. Add boundary, ordering, NULL, subclass, and recovery regression coverage.

Validation: 2,287 related runtime tests passed, with 64 existing/platform/build-dependent skips; 4 strict typing checks passed; pinned full-directory formatting and git diff --check passed. Validation used Windows x64, Python 3.13.17, and SQL Server 15.0.4382.1. Cross-platform CI is still required.

Native metadata computation avoids Python character loops and encoded copies. Local long-Unicode benchmarks were 61–76% faster than the earlier correct fix. Comparisons with original HEAD had small variable differences; no zero-overhead guarantee. Incompatible mixed types use slower individual execution to preserve values.

Infer Unicode and UTF-16 capacity across batches, preserve numeric shapes and text payloads, and use native metadata collection to avoid Python character loops.

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

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

PR Performance Report

✅ No regression detected

No consistent slowdowns detected across all 2 environments.

0 IMPROVEMENTS 0 SLOWDOWNS 2/2 ENVIRONMENTS

Coverage: 2 of 2 environments completed. Advisory result; does not block merging.

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

256 KiB VARCHAR(MAX) / fetchall(): ddbc::SQLGetData_wrap +0.223 ms; ddbc::FetchLobColumnData +0.223 ms; ddbc::FetchAll_wrap +0.206 ms. Call changes: ddbc::AppendDiagRecords::SQLGetDiagField_call (128 -> 2 calls).

Unix / SQL Server 2025

256 KiB VARCHAR(MAX) / fetchall(): ddbc::SQLGetData_wrap +0.584 ms; py::fetchall::cpp_call +0.584 ms; ddbc::FetchLobColumnData +0.584 ms. Call changes: ddbc::AppendDiagRecords::SQLGetDiagField_call (128 -> 2 calls).

All database tasks and timings

Unix / SQL Server 2022

Database task Before After Paired change Result
Connection opening 9.916 ms 10.009 ms +0.3% no signal
SELECT queries 0.974 ms 0.969 ms +0.7% no signal
Row insertion 30.522 ms 30.641 ms +0.5% no signal
Executemany inserts 163.930 ms 166.114 ms +1.3% no signal
Fetch-all queries 116.285 ms 119.022 ms +2.7% no signal
Row-by-row fetching 4.893 ms 4.831 ms -1.1% no signal
Batched row fetching 115.227 ms 114.545 ms +0.9% no signal
Transaction commit and rollback 105.695 ms 107.945 ms +0.7% no signal
Arrow row fetching 91.145 ms 88.701 ms +0.2% no signal
100,000-row insertion 351.887 ms 368.189 ms -0.8% no signal
Row fetching in batches of 100 119.884 ms 131.232 ms +2.4% no signal
Row fetching in batches of 10,000 141.289 ms 130.343 ms -6.6% no signal
Repeated positional queries 31.951 ms 32.855 ms -0.1% no signal
Repeated named-parameter queries 32.365 ms 32.119 ms -1.2% no signal
Legacy 100,000-row insertion 268.088 ms 265.151 ms -1.1% no signal
Insertion with explicit input sizes 415.970 ms 402.113 ms -4.1% no signal
Joined aggregation queries 178.081 ms 180.095 ms +0.3% no signal
Large joined-result fetching 185.442 ms 187.567 ms +1.7% no signal
1.2-million-row fetching 3396.861 ms 3420.123 ms +0.7% no signal
Common table expression queries 5.245 ms 5.227 ms +0.4% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.442 ms 1.648 ms +14.3% no signal
10,000 scalar values / fetchval() (debug disabled) 16.626 ms 16.434 ms -0.8% no signal
10,000 output-converted rows / fetchall() 19.224 ms 19.279 ms +0.7% no signal
10,000 output-converted rows / fetchmany(1000) 23.626 ms 22.798 ms -2.8% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 23.939 ms 24.060 ms +0.7% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 30.934 ms 30.509 ms -1.3% no signal

Unix / SQL Server 2025

Database task Before After Paired change Result
Connection opening 80.992 ms 81.720 ms +0.8% no signal
SELECT queries 1.141 ms 0.999 ms -10.3% no signal
Row insertion 30.407 ms 30.940 ms -1.7% no signal
Executemany inserts 161.094 ms 152.626 ms -6.3% no signal
Fetch-all queries 120.594 ms 121.282 ms +0.7% no signal
Row-by-row fetching 4.918 ms 4.892 ms +0.1% no signal
Batched row fetching 115.877 ms 117.879 ms +1.6% no signal
Transaction commit and rollback 105.068 ms 107.936 ms +2.3% no signal
Arrow row fetching 89.160 ms 89.057 ms -0.1% no signal
100,000-row insertion 359.362 ms 365.858 ms -0.7% no signal
Row fetching in batches of 100 120.428 ms 121.137 ms +2.3% no signal
Row fetching in batches of 10,000 143.959 ms 134.662 ms -5.4% no signal
Repeated positional queries 31.613 ms 31.300 ms -0.7% no signal
Repeated named-parameter queries 31.864 ms 31.566 ms -0.7% no signal
Legacy 100,000-row insertion 267.391 ms 266.442 ms -0.8% no signal
Insertion with explicit input sizes 415.977 ms 421.072 ms +1.7% no signal
Joined aggregation queries 164.092 ms 163.344 ms -0.3% no signal
Large joined-result fetching 193.316 ms 192.284 ms +1.2% no signal
1.2-million-row fetching 3452.926 ms 3497.720 ms +0.7% no signal
Common table expression queries 5.196 ms 5.266 ms +1.5% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.433 ms 2.017 ms +2.9% no signal
10,000 scalar values / fetchval() (debug disabled) 17.044 ms 16.664 ms -3.1% no signal
10,000 output-converted rows / fetchall() 19.301 ms 19.322 ms -1.6% no signal
10,000 output-converted rows / fetchmany(1000) 24.675 ms 33.589 ms +5.9% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 24.622 ms 24.130 ms -1.2% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 31.172 ms 31.330 ms +0.5% no signal
Build and measurement details

ADO build 194437

PR head: 7cbf362e47b9eb615984c051054b34fde5465d07
Base: f3cc8c97c61d469def72e199fcfaf17e092d3b5c
Measured merge: 15904cba92dca2b45431787392980619462d94ee

  • Unix / SQL Server 2022: Python 3.12.3, x86_64, SQL 16.0.4325.4; 5 paired comparisons and 1 warmup.
  • Unix / SQL Server 2025: Python 3.12.3, x86_64, SQL 17.0.5065.9; 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.

Comment thread tests/test_004_cursor.py Fixed

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

The mixed-type fallback passes generic row sequences such as UserList as a single parameter instead of unpacking their values, violating the supported input contract.

1 open issue
What changed in this PR

This PR improves executemany() value preservation across the Python cursor and native bindings, covering Unicode, Decimal, mixed-type batches, and embedded NUL characters.

Changes:

  • Infer text sizes and Decimal precision across entire columns, using individual execution when array binding cannot preserve values.
  • Separate text buffer capacity from SQL precision and preserve NUL characters during binding and retrieval.
  • Add regression coverage and document inference, overrides, and fallback rowcounts.
File Description
tests/​test_013_encoding_decoding.py Tests NUL preservation across large-text fetch paths.
tests/​test_004_cursor.py Adds batch inference, boundary, override, and recovery tests.
README.md Documents batch inference and fallback behavior.
mssql_python/​pybind/​param_detect.hpp Adds native text metadata and separate buffer capacity.
mssql_python/​pybind/​ddbc_bindings.cpp Uses explicit text lengths and preserves fetched NULs.
mssql_python/​ddbc_bindings.py Exposes the native batch metadata helper to typing.
mssql_python/​cursor.py Implements lossless column inference and aggregates fallback rowcounts.
mssql_python/​_ddbc_types.pyi Types the new metadata helper and buffer-size field.

Review effort: Balanced

Comment thread mssql_python/cursor.py Resolved
Copilot AI balanced review requested due to automatic review settings November 19, 2026 09:42

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

The fallback to individual execution bypasses DECIMAL/NUMERIC override conversion and rejects valid inputs, while mixed built-in and subclass strings unnecessarily lose array binding.

3 open issues

Review effort: Balanced

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 19, 2026 10:59

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 mixed-type fallback bypasses DECIMAL/NUMERIC override conversion and mishandles custom sequence rows, causing previously valid executemany inputs to fail.

3 open issues

Review effort: Balanced

Normalize generic row sequences and explicit numeric overrides for fallback execution, keep compatible text subclasses in array binding, and use deterministic generated cases without a random generator.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 19, 2026 11:09

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 text parameters still incur per-character Python scans before native metadata handling, undermining the intended performance improvement.

No open issues 🎉

3 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 19, 2026 11:40

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 LOB accounting and array-binding changes require human review of cross-platform CI evidence because reported runtime validation covers only Windows x64, and this review could not build the extension or run SQL Server integration checks.

No open issues 🎉

Review effort: Balanced

Probe the source byte length before VARCHAR-to-UTF-16 LOB conversion to avoid driver character loss at truncated surrogate boundaries. Preserve chunked XML, NVARCHAR, narrow-text and binary paths; expand NUL and boundary coverage.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 19, 2026 12: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

Human assessment is needed because mixed-type fallback can discard inferred binary NULL types and trigger conversion failures, and this combined case remains unverified against a live server.

No open issues 🎉

Review effort: Balanced

Replace the range insertion rejected by newer GCC overflow analysis with checked buffer growth and an explicit byte copy. Retain the wide-conversion allocation and existing NUL-preserving byte accounting.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 20, 2026 01:22

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 mixed-column rowwise fallback can skip Decimal-to-text conversion for explicit SQL_VARCHAR overrides, causing parameter binding to fail.

No open issues 🎉

Review effort: Balanced

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

📊 Code Coverage Report

🔥 Diff Coverage

92%


🎯 Overall Coverage

86%


📈 Total Lines Covered: 12185 out of 14136
📁 Project: mssql-python


Diff Coverage

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

  • mssql_python/cursor.py (100%)
  • mssql_python/pybind/ddbc_bindings.cpp (85.2%): Missing lines 2581,2712,2721,3475-3476,3550,3870,3886
  • mssql_python/pybind/ddbc_bindings.h (0.0%): Missing lines 725
  • mssql_python/pybind/param_detect.hpp (93.1%): Missing lines 309-310

Summary

  • Total: 155 lines
  • Missing: 11 lines
  • Coverage: 92%

mssql_python/pybind/ddbc_bindings.cpp

Lines 2577-2585

  2577                         } else {
  2578                             std::u16string wstr = columnValues[i].cast<std::u16string>();
  2579                             // u16string is already UTF-16, so the
  2580                             // original check is sufficient
! 2581                             if (wstr.length() > bufferSize) {
  2582                                 ThrowStdException("Input string exceeds allowed column size "
  2583                                                   "at parameter index " +
  2584                                                   std::to_string(paramIndex));
  2585                             }

Lines 2708-2716

  2708                                     paramIndex, i, encodedStr.size(), info.columnSize);
  2709                                 ThrowStdException("Input exceeds column size at index " +
  2710                                                   std::to_string(i));
  2711                             }
! 2712                             std::memcpy(charArray + i * (bufferSize + 1), encodedStr.c_str(),
  2713                                         encodedStr.size());
  2714                             strLenOrIndArray[i] = static_cast<SQLLEN>(encodedStr.size());
  2715                         }
  2716                     }

Lines 2717-2725

  2717                     LOG("BindParameterArray: SQL_C_CHAR/BINARY bound - "
  2718                         "param_index=%d",
  2719                         paramIndex);
  2720                     dataPtr = charArray;
! 2721                     bufferLength = bufferSize + 1;
  2722                     break;
  2723                 }
  2724                 case SQL_C_BIT: {
  2725                     LOG("BindParameterArray: Binding SQL_C_BIT array - "

Lines 3471-3480

  3471     int loopCount = 0;
  3472     size_t chunkSize = DAE_CHUNK_SIZE;
  3473     if (sizeWideConversion) {
  3474         // Unix drivers can consume characters that do not fit during a truncated
! 3475         // VARCHAR-to-WCHAR conversion. A binary probe does not consume data and
! 3476         // bounds UTF-16 output by two bytes per source byte, plus the terminator.
  3477         SQLLEN sourceLength = 0;
  3478         {
  3479             py::gil_scoped_release release;
  3480             ret = SQLGetData_ptr(hStmt, colIndex, SQL_C_BINARY, nullptr, 0, &sourceLength);

Lines 3546-3554

  3546             } else {
  3547                 if (bytesRead > buffer.max_size() - buffer.size()) {
  3548                     ThrowStdException("SQLGetData LOB exceeds the maximum buffer size");
  3549                 }
! 3550                 const size_t offset = buffer.size();
  3551                 buffer.resize(offset + bytesRead);
  3552                 std::copy_n(chunk.data(), bytesRead, buffer.data() + offset);
  3553             }
  3554             LOG("FetchLobColumnData: Appended %zu bytes at loop %d", bytesRead, loopCount);

Lines 3866-3874

  3866                                 LOG("SQLGetData: CHAR column %d (WCHAR path) data "
  3867                                     "truncated, using streaming LOB",
  3868                                     i);
  3869                                 row.append(FetchLobColumnData(hStmt, i, SQL_C_WCHAR, true, false,
! 3870                                                               "utf-16le", messages, true));
  3871                             }
  3872                         } else if (dataLen == SQL_NULL_DATA) {
  3873                             LOG("SQLGetData: Column %d is NULL (CHAR via WCHAR)", i);
  3874                             row.append(py::none());

Lines 3882-3890

  3882                             LOG("SQLGetData: SQL_NO_TOTAL for column %d (CHAR via WCHAR), "
  3883                                 "streaming via FetchLobColumnData",
  3884                                 i);
  3885                             row.append(FetchLobColumnData(hStmt, i, SQL_C_WCHAR, true, false,
! 3886                                                           "utf-16le", messages, true));
  3887                         } else if (dataLen < 0) {
  3888                             LOG("SQLGetData: Unexpected negative data length "
  3889                                 "for column %d - dataType=%d, dataLen=%ld",
  3890                                 i, dataType, (long)dataLen);

mssql_python/pybind/ddbc_bindings.h

  721         } else {
  722             // LOB / truncated: stream with SQL_C_WCHAR
  723             PyList_SET_ITEM(row, col - 1,
  724                             FetchLobColumnData(hStmt, col, SQL_C_WCHAR, true, false, "utf-16le",
! 725                                                py::handle(colInfo->messages), true)
  726                                 .release()
  727                                 .ptr());
  728         }
  729         return;

mssql_python/pybind/param_detect.hpp

Lines 305-314

  305         if (value == Py_None) {
  306             continue;
  307         }
  308         if (!PyUnicode_Check(value)) {
! 309             throw py::type_error("Batch text metadata requires str or None values");
! 310         }
  311         needsUnicode = needsUnicode || !PyUnicode_IS_ASCII(value);
  312         maxLength = std::max(maxLength, UnicodeUtf16Length(value));
  313     }
  314     return {needsUnicode, maxLength};


📋 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: 64.8%
mssql_python.pybind.logger_bridge.hpp: 70.8%
mssql_python._native_fetch.py: 77.7%
mssql_python.pybind.ddbc_bindings.cpp: 81.1%
mssql_python.__init__.py: 81.2%
mssql_python.pybind.row_mapping_cache.hpp: 81.5%
mssql_python.pybind.connection.connection.cpp: 82.9%
mssql_python.pybind.connection.connection_pool.cpp: 83.1%

🔗 Quick Links

⚙️ Build Summary 📋 Coverage Details

View Azure DevOps Build

Browse Full Coverage Report

Use the server connection GUID instead of a reusable SPID when observing native teardown. Open the replacement before polling to exercise immediate session-slot reuse while preserving rollback, lock-release, and physical-disconnect assertions.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 20, 2026 01:48

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

The pooling test fails for logins lacking permission to read sys.dm_exec_connections before reaching the skip handler; the initial query must exit with code 77 for permission errors while preserving other failures.

1 open issue

Review effort: Balanced

Comment thread tests/test_009_pooling.py Resolved
Use the standard-library copy algorithm after checked LOB buffer growth. Inspect native DMV query diagnostics and skip only permission denials, retaining SQLSTATE and message for other failures.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 20, 2026 03:15

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

Reported validation is Windows-only, while platform-sensitive SQLGetData probing and UTF-16 chunk handling require Linux/macOS integration checks that this environment cannot run.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

Preserve the TVP executemany guard from main and the lossless batch Decimal buffer sizing.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 23, 2026 13:45

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

Reported Windows-only validation leaves driver-dependent SQLGetData probing and rowwise fallback unverified on Linux/macOS, particularly SQL_NO_TOTAL handling and typed NULLs in temporary tables.

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.

3 participants