Repository navigation
FIX: Preserve executemany values with lossless batch inference - #907
Jahnvi Thakkar (jahnvi480) wants to merge 10 commits into
Conversation
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>
PR Performance Report✅ No regression detectedNo 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 diagnosticsPhase times are inclusive diagnostics and must not be added together. They identify where measured time changed, not why it changed. Unix / SQL Server 2022256 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 2025256 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 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.
🟡 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
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>
There was a problem hiding this comment.
🔵 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
There was a problem hiding this comment.
🔵 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>
There was a problem hiding this comment.
🔵 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>
📊 Code Coverage Report
Diff CoverageDiff: main...HEAD, staged and unstaged changes
Summary
mssql_python/pybind/ddbc_bindings.cppLines 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.hmssql_python/pybind/param_detect.hppLines 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
|
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>
There was a problem hiding this comment.
🟡 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
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>
There was a problem hiding this comment.
🔵 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>
There was a problem hiding this comment.
🔵 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


Work Item / Issue Reference
Summary
Fix lossless
executemanyinference 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 --checkpassed. 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.