Skip to content

FIX: Validate caller-controlled native buffer sizes - #802

Open
gargsaumya wants to merge 69 commits into
mainfrom
saumya/native-size-validation
Open

gargsaumya wants to merge 69 commits into
mainfrom
saumya/native-size-validation

Conversation

@gargsaumya

@gargsaumya gargsaumya commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Work Item / Issue Reference

ADO Work Item: AB#47843


Summary

  • Reject invalid Python row counts before crossing native boundaries.
  • Check parameter allocation arithmetic and metadata cardinality.
  • Tighten binary and wide-character input validation.

No tracking issue exists for this security hardening work.

Copilot AI lite review requested due to automatic review settings September 21, 2026 06:53
@github-actions

github-actions Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

PR Performance Report

⚠️ Performance regression detected

1 database task consistently slowed down across 2 measured environments.

0 IMPROVEMENTS 1 SLOWDOWN 2/2 ENVIRONMENTS

1 INCONSISTENT SLOWDOWN

Signal fingerprint

Database task Unix / SQL Server 2022 Unix / SQL Server 2025
Insertion with explicit input sizes 33.6% slower 32.4% slower
5,000 x 8 VARCHAR(8000) / ASCII to UTF-16 27.0% inconsistent No signal

The largest recorded phase increases for these tasks are shown below. Phase timings are supporting evidence, not root-cause proof.
1 additional inconsistent slowdown also need review.

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

Measured timings
Environment Database task Before After Change
Unix / SQL Server 2022 Insertion with explicit input sizes 418.218 ms 546.349 ms +33.6%
Unix / SQL Server 2022 5,000 x 8 VARCHAR(8000) / ASCII to UTF-16 44.626 ms 45.966 ms +27.0%
Unix / SQL Server 2025 Insertion with explicit input sizes 423.004 ms 548.371 ms +32.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

Insertion with explicit input sizes: py::execute::cpp_call +24.287 ms; ddbc::SQLExecute_wrap +23.604 ms; ddbc::BindParameters::SQLBindParameter_call +0.346 ms.
5,000 x 8 VARCHAR(8000) / ASCII to UTF-16: ddbc::FetchBatchData +3.622 ms; ddbc::FetchBatchData::SQLFetchScroll_call +2.728 ms; py::fetchall::cpp_call +1.365 ms.

Unix / SQL Server 2025

Insertion with explicit input sizes: py::execute::cpp_call +20.328 ms; ddbc::SQLExecute_wrap +19.767 ms; ddbc::BindParameters +1.784 ms.

All database tasks and timings

Unix / SQL Server 2022

Database task Before After Paired change Result
Connection opening 10.518 ms 10.571 ms +0.5% no signal
SELECT queries 1.342 ms 1.490 ms +15.7% no signal
Row insertion 31.922 ms 32.847 ms +1.9% no signal
Executemany inserts 158.664 ms 161.033 ms +1.8% no signal
Fetch-all queries 120.589 ms 122.864 ms +1.1% no signal
Row-by-row fetching 6.068 ms 6.380 ms +6.0% no signal
Batched row fetching 122.221 ms 118.980 ms -3.6% no signal
Transaction commit and rollback 110.137 ms 108.371 ms -0.5% no signal
Arrow row fetching 91.329 ms 100.663 ms +8.9% no signal
100,000-row insertion 358.458 ms 376.420 ms +5.0% no signal
Row fetching in batches of 100 122.737 ms 125.902 ms +3.8% no signal
Row fetching in batches of 10,000 122.438 ms 124.631 ms +2.5% no signal
Repeated positional queries 33.994 ms 33.825 ms -0.2% no signal
Repeated named-parameter queries 34.019 ms 34.117 ms +3.2% no signal
Legacy 100,000-row insertion 294.419 ms 273.162 ms -8.1% no signal
Insertion with explicit input sizes 418.218 ms 546.349 ms +33.6% consistent slowdown
Joined aggregation queries 180.935 ms 181.659 ms +0.3% no signal
Large joined-result fetching 191.005 ms 190.181 ms +0.2% no signal
1.2-million-row fetching 3531.966 ms 3565.024 ms +0.9% no signal
Common table expression queries 5.642 ms 5.590 ms +0.0% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.343 ms 1.323 ms -2.0% no signal
10,000 scalar values / fetchval() (debug disabled) 19.416 ms 19.659 ms +1.3% no signal
10,000 output-converted rows / fetchall() 20.193 ms 20.222 ms +0.1% no signal
10,000 output-converted rows / fetchmany(1000) 25.018 ms 24.415 ms -1.3% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 27.971 ms 28.108 ms -0.7% no signal
5,000 x 8 VARCHAR(8000) / ASCII to UTF-16 44.626 ms 45.966 ms +27.0% inconsistent slowdown
5,000 x 8 VARCHAR(8000) / CP1252 to UTF-16 58.809 ms 58.881 ms +0.3% no signal
5,000 x 8 VARCHAR(8000) / UTF-8 to UTF-16 (astral) 111.502 ms 113.340 ms +7.8% no signal
5,000 x 8 NVARCHAR(4000) / UTF-16 (astral) 87.533 ms 92.247 ms -2.6% no signal
5,000 x 8 VARCHAR(8000) / short ASCII 10.301 ms 10.211 ms -3.1% no signal
200 x 8 VARCHAR(8000) / full-width ASCII 45.419 ms 44.154 ms -13.8% no signal
5,000 x 8 VARCHAR(8000) / short CP1252 12.388 ms 12.762 ms +2.6% no signal
200 x 8 VARCHAR(8000) / full-width CP1252 43.457 ms 43.208 ms +1.0% no signal
5,000 x 8 VARCHAR(8000) / short UTF-8 (astral) 15.801 ms 15.938 ms -1.3% no signal
200 x 8 VARCHAR(8000) / full-width UTF-8 (astral) 45.937 ms 48.047 ms +10.7% no signal
5,000 x 8 NVARCHAR(4000) / short UTF-16 (astral) 14.402 ms 14.321 ms -0.6% no signal
200 x 8 NVARCHAR(4000) / full-width UTF-16 (astral) 61.950 ms 61.109 ms -4.0% no signal
200,000 x 8 VARCHAR(32) / fetchall control 551.018 ms 522.603 ms -4.8% no signal
200,000 x 8 INT / fetchall control 281.601 ms 283.987 ms +1.2% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 31.589 ms 31.203 ms -0.8% no signal

Unix / SQL Server 2025

Database task Before After Paired change Result
Connection opening 81.126 ms 81.888 ms +0.5% no signal
SELECT queries 1.292 ms 1.306 ms +1.4% no signal
Row insertion 32.772 ms 32.516 ms +0.3% no signal
Executemany inserts 154.560 ms 153.921 ms -1.3% no signal
Fetch-all queries 121.244 ms 123.995 ms +2.4% no signal
Row-by-row fetching 6.069 ms 6.187 ms +0.5% no signal
Batched row fetching 118.276 ms 120.328 ms +1.3% no signal
Transaction commit and rollback 112.553 ms 111.830 ms -2.3% no signal
Arrow row fetching 91.674 ms 100.614 ms +9.6% no signal
100,000-row insertion 367.889 ms 389.208 ms +5.5% no signal
Row fetching in batches of 100 124.876 ms 128.618 ms +2.2% no signal
Row fetching in batches of 10,000 123.287 ms 128.951 ms +4.6% no signal
Repeated positional queries 34.027 ms 35.056 ms +2.8% no signal
Repeated named-parameter queries 34.233 ms 34.621 ms +1.1% no signal
Legacy 100,000-row insertion 295.086 ms 282.485 ms -0.4% no signal
Insertion with explicit input sizes 423.004 ms 548.371 ms +32.4% consistent slowdown
Joined aggregation queries 165.532 ms 165.415 ms +0.4% no signal
Large joined-result fetching 186.226 ms 190.455 ms +1.5% no signal
1.2-million-row fetching 3519.942 ms 3526.912 ms +1.0% no signal
Common table expression queries 5.406 ms 5.222 ms -2.5% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.401 ms 1.660 ms +25.7% no signal
10,000 scalar values / fetchval() (debug disabled) 19.813 ms 19.499 ms -1.0% no signal
10,000 output-converted rows / fetchall() 19.802 ms 19.545 ms -1.6% no signal
10,000 output-converted rows / fetchmany(1000) 23.901 ms 24.103 ms +4.0% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 28.098 ms 28.285 ms +0.6% no signal
5,000 x 8 VARCHAR(8000) / ASCII to UTF-16 44.351 ms 50.536 ms +17.8% no signal
5,000 x 8 VARCHAR(8000) / CP1252 to UTF-16 57.683 ms 62.094 ms +14.6% no signal
5,000 x 8 VARCHAR(8000) / UTF-8 to UTF-16 (astral) 102.218 ms 120.019 ms +16.2% no signal
5,000 x 8 NVARCHAR(4000) / UTF-16 (astral) 124.113 ms 128.046 ms +1.5% no signal
5,000 x 8 VARCHAR(8000) / short ASCII 10.359 ms 10.226 ms -0.7% no signal
200 x 8 VARCHAR(8000) / full-width ASCII 53.998 ms 50.855 ms -4.0% no signal
5,000 x 8 VARCHAR(8000) / short CP1252 12.925 ms 12.610 ms -1.7% no signal
200 x 8 VARCHAR(8000) / full-width CP1252 50.161 ms 49.999 ms -0.4% no signal
5,000 x 8 VARCHAR(8000) / short UTF-8 (astral) 15.998 ms 16.192 ms -1.1% no signal
200 x 8 VARCHAR(8000) / full-width UTF-8 (astral) 52.909 ms 54.475 ms +2.7% no signal
5,000 x 8 NVARCHAR(4000) / short UTF-16 (astral) 14.407 ms 14.738 ms +1.3% no signal
200 x 8 NVARCHAR(4000) / full-width UTF-16 (astral) 75.658 ms 76.344 ms -1.0% no signal
200,000 x 8 VARCHAR(32) / fetchall control 525.136 ms 511.492 ms +0.5% no signal
200,000 x 8 INT / fetchall control 271.474 ms 267.197 ms -0.5% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 31.390 ms 31.120 ms -2.1% no signal
Build and measurement details

ADO build 195542

PR head: 81dc350b08aad46354cb564ae14f275e816ca95e
Base: 239f79fd87f01b7b5716762f943c7b143fdf8e1b
Measured merge: 8efde89821b3522929d8523f74bd8dca7258df66

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

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.

Copilot review overview

🟡 Changes recommended

Unresolved row-count and binary validation gaps remain, and an existing Arrow batch-size test requires reconciliation.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 1 High severity · 1 Medium severity

Open (2)
What changed in this PR

Hardens Python-to-native boundary validation for row counts, allocations, metadata, and binary inputs.

Changes:

  • Adds row-count, boolean, and input-size validation.
  • Adds native allocation overflow and metadata checks.
  • Tightens binary and wide-character handling with regression tests.
File Description
tests/​test_024_bulkcopy_arrow.py Tests boolean batch-size rejection.
tests/​test_004_cursor.py Tests cursor size and metadata validation.
mssql_python/​pybind/​ddbc_bindings.cpp Adds native allocation and parameter validation.
mssql_python/​cursor.py Validates row counts and input sizes.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread mssql_python/cursor.py Resolved
Comment thread mssql_python/pybind/ddbc_bindings.cpp Resolved
Copilot AI review requested due to automatic review settings September 21, 2026 07:27

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.

Copilot review overview

🟡 Changes recommended

Native paths still permit dangerous negative or extremely large allocations, and arrow_reader() does not reject invalid sizes synchronously.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 4 High severity · 1 Medium severity

Open (5)

Comment thread mssql_python/cursor.py Resolved
Comment thread mssql_python/pybind/ddbc_bindings.cpp Resolved
Comment thread mssql_python/pybind/ddbc_bindings.cpp Resolved
@github-actions

github-actions Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

📊 Code Coverage Report

🔥 Diff Coverage

88%


🎯 Overall Coverage

87%


📈 Total Lines Covered: 15113 out of 17332
📁 Project: mssql-python


Diff Coverage

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

  • mssql_python/cursor.py (82.1%): Missing lines 97-109,3143
  • mssql_python/pybind/connection/connection.cpp (94.7%): Missing lines 343
  • mssql_python/pybind/ddbc_bindings.cpp (88.7%): Missing lines 332-333,342-343,349-350,366-367,371-378,386-387,399-400,424,430,452-453,498-499,518-520,530-531,536-537,542-543,545,551-552,643,686-687,698-699,716-717,726-727,741-742,749-750,1002,2492,2733-2734,2781,2835,2858-2859,3000,3306,3378-3381,3410-3411,3444,3449,3453-3454,3875-3877,3886-3888,3895-3897,3912-3913,4027-4028,4067,4244-4245,4251-4252,4270-4271,4308-4309,4325,4363,4766,5150,5240,5779-5780,5827,5830,5900-5901,5932-5933,5960-5961,6246-6247,6256-6257,6321-6322,6420,6573,6599-6600,6602,6617-6618,6940-6941,6952-6953,6959-6960,6984-6985,6989-6990,7026,7032-7034,7037-7043,7065-7087,7091-7103,7148-7149,7290,7404,7417-7419,7494-7495,7558,7646-7647,7747,7907-7908,7912,8335-8339
  • mssql_python/pybind/ddbc_bindings.h (94.1%): Missing lines 415-416
  • mssql_python/pybind/native_fetch.hpp (66.7%): Missing lines 738
  • mssql_python/pybind/param_detect.hpp (85.9%): Missing lines 159,162,165,168,255-256,260-262,293-294,298-300,316-317,337-338,346-347,352-353,361-362,374-375,537-538
  • mssql_python/pybind/tvp.hpp (100%)

Summary

  • Total: 2090 lines
  • Missing: 245 lines
  • Coverage: 88%

mssql_python/cursor.py

Lines 93-113

   93 MAX_NATIVE_PARAMETER_SIZE: int = 256 * 1024 * 1024
   94 
   95 
   96 def _encoded_length_exceeds(value: str, encoding: str, limit: int) -> bool:
!  97     encoder = codecs.getincrementalencoder(encoding)(errors="strict")
!  98     total = 0
!  99     chunk_size = 4096
! 100     value_length = str.__len__(value)
! 101     for offset in range(0, value_length, chunk_size):
! 102         end = min(offset + chunk_size, value_length)
! 103         chunk = str.__getitem__(value, slice(offset, end))
! 104         total += len(encoder.encode(chunk, final=end == value_length))
! 105         if total > limit:
! 106             return True
! 107     if value_length == 0:
! 108         total += len(encoder.encode("", final=True))
! 109     return total > limit
  110 
  111 
  112 def _utf16_length_exceeds(value: str, limit: int) -> bool:
  113     bounded_value = str.__getitem__(value, slice(0, limit + 1))

Lines 3139-3147

  3139                         binary_values = [
  3140                             value for value in column if isinstance(value, (bytes, bytearray))
  3141                         ]
  3142                         if c_type == ddbc_sql_const.SQL_CHAR.value:
! 3143                             text_is_large = any(
  3144                                 _encoded_length_exceeds(
  3145                                     value,
  3146                                     encoding_settings["encoding"],
  3147                                     MAX_INLINE_CHAR,

mssql_python/pybind/connection/connection.cpp

Lines 339-347

  339     }
  340     // Only successful native sanitation with no retained statement/raw handle
  341     // aliases proves ON. A new login or _autocommit alone is not proof.
  342     if (!force && enable && _dbcHandle->get() && _poolClean && !_poolProofDisabled) {
! 343         clearResultMetadata();
  344         _autocommit = true;
  345         return;
  346     }
  347     SQLINTEGER value = enable ? SQL_AUTOCOMMIT_ON : SQL_AUTOCOMMIT_OFF;

mssql_python/pybind/ddbc_bindings.cpp

Lines 328-337

  328 
  329 template <typename ParamType>
  330 ParamType* AllocateParamBufferArray(std::vector<std::shared_ptr<void>>& paramBuffers,
  331                                     size_t count) {
! 332     if (count > std::numeric_limits<size_t>::max() / sizeof(ParamType)) {
! 333         ThrowStdException("Parameter buffer size is too large");
  334     }
  335     std::shared_ptr<ParamType> buffer(new ParamType[count], std::default_delete<ParamType[]>());
  336     ParamType* raw = buffer.get();
  337     paramBuffers.push_back(buffer);

Lines 338-347

  338     return raw;
  339 }
  340 
  341 size_t CheckedAddSize(size_t left, size_t right, const char* errorMessage) {
! 342     if (left > std::numeric_limits<size_t>::max() - right) {
! 343         ThrowStdException(errorMessage);
  344     }
  345     return left + right;
  346 }

Lines 345-354

  345     return left + right;
  346 }
  347 
  348 size_t CheckedMultiplySize(size_t left, size_t right, const char* errorMessage) {
! 349     if (left != 0 && right > std::numeric_limits<size_t>::max() / left) {
! 350         ThrowStdException(errorMessage);
  351     }
  352     return left * right;
  353 }

Lines 362-382

  362 }
  363 
  364 size_t CheckedFetchColumnSize(SQLULEN columnSize) {
  365     const size_t result = static_cast<size_t>(columnSize);
! 366     if (static_cast<SQLULEN>(result) != columnSize) {
! 367         ThrowStdException("Column size is too large");
  368     }
  369     return result;
  370 }
! 371 
! 372 SQLLEN CheckedFetchBufferLength(size_t elementCount, size_t elementSize) {
! 373     const size_t byteCount =
! 374         CheckedMultiplySize(elementCount, elementSize, "Column fetch stride is too large");
! 375     if (byteCount > static_cast<size_t>(std::numeric_limits<SQLLEN>::max())) {
! 376         ThrowStdException("Column fetch stride is too large");
! 377     }
! 378     return static_cast<SQLLEN>(byteCount);
  379 }
  380 
  381 template <typename ElementType>
  382 size_t CheckedArrowSourceOffset(const std::vector<ElementType>& buffer, size_t rowIndex,

Lines 382-391

  382 size_t CheckedArrowSourceOffset(const std::vector<ElementType>& buffer, size_t rowIndex,
  383                                 size_t stride, size_t dataBytes) {
  384     const size_t offset =
  385         CheckedMultiplySize(rowIndex, stride, "Arrow source offset is too large");
! 386     if (offset > buffer.size() || stride > buffer.size() - offset) {
! 387         ThrowStdException("Driver data length exceeds the allocated fetch buffer");
  388     }
  389     const size_t availableBytes =
  390         CheckedMultiplySize(stride, sizeof(ElementType), "Arrow source size is too large");
  391     if (dataBytes > availableBytes) {

Lines 395-404

  395 }
  396 
  397 template <typename ElementType>
  398 void ValidateArrowTextPayloadLength(size_t stride, size_t dataBytes) {
! 399     if (stride == 0) {
! 400         ThrowStdException("Arrow text fetch buffer has no terminator storage");
  401     }
  402     const size_t payloadBytes = CheckedMultiplySize(
  403         stride - 1, sizeof(ElementType), "Arrow text source size is too large");
  404     if (dataBytes > payloadBytes) {

Lines 420-428

  420         case SQL_FLOAT:
  421         case SQL_DOUBLE:
  422             return sizeof(SQLDOUBLE);
  423         case SQL_BIGINT:
! 424             return sizeof(SQLBIGINT);
  425         case SQL_TIMESTAMP:
  426         case SQL_TYPE_TIMESTAMP:
  427         case SQL_DATETIME:
  428             return sizeof(SQL_TIMESTAMP_STRUCT);

Lines 426-434

  426         case SQL_TYPE_TIMESTAMP:
  427         case SQL_DATETIME:
  428             return sizeof(SQL_TIMESTAMP_STRUCT);
  429         case SQL_TYPE_DATE:
! 430             return sizeof(SQL_DATE_STRUCT);
  431         case SQL_TYPE_TIME:
  432         case SQL_SS_TIME2:
  433             return sizeof(SQL_SS_TIME2_STRUCT);
  434         case SQL_GUID:

Lines 448-457

  448 }
  449 
  450 void ValidateDirectFetchDataLength(SQLRETURN ret, SQLSMALLINT dataType, SQLLEN indicator) {
  451     if (SQL_SUCCEEDED(ret) && indicator != SQL_NULL_DATA) {
! 452         if (indicator < 0) {
! 453             ThrowStdException("Unexpected negative data length");
  454         }
  455         ValidateFixedFetchDataLength(dataType, static_cast<uint64_t>(indicator));
  456     }
  457 }

Lines 494-503

  494 }
  495 
  496 size_t ParameterArrayElementSize(const ParamInfo& info) {
  497     const SQLULEN bufferSize = std::max(info.columnSize, info.arrayBufferSize);
! 498     switch (info.paramCType) {
! 499         case SQL_C_SS_VECTOR:
  500             return info.columnSize;
  501         case SQL_C_LONG:
  502             return sizeof(int);
  503         case SQL_C_DOUBLE:

Lines 514-524

  514         case SQL_C_CHAR:
  515         case SQL_C_BINARY:
  516             return CheckedAddSize(bufferSize, 1, "Character parameter size is too large");
  517         case SQL_C_BIT:
! 518             return sizeof(char);
! 519         case SQL_C_STINYINT:
! 520         case SQL_C_USHORT:
  521             return sizeof(unsigned short);
  522         case SQL_C_SBIGINT:
  523         case SQL_C_SLONG:
  524         case SQL_C_UBIGINT:

Lines 526-549

  526             return sizeof(int64_t);
  527         case SQL_C_FLOAT:
  528             return sizeof(float);
  529         case SQL_C_TYPE_DATE:
! 530             return sizeof(SQL_DATE_STRUCT);
! 531         case SQL_C_TYPE_TIME:
  532             return sizeof(SQL_TIME_STRUCT);
  533         case SQL_C_TYPE_TIMESTAMP:
  534             return sizeof(SQL_TIMESTAMP_STRUCT);
  535         case SQL_C_SS_TIMESTAMPOFFSET:
! 536             return sizeof(DateTimeOffset);
! 537         case SQL_C_NUMERIC:
  538             return sizeof(SQL_NUMERIC_STRUCT);
  539         case SQL_C_GUID:
  540             return sizeof(SQLGUID);
  541         case SQL_C_DEFAULT:
! 542             return sizeof(char);
! 543         default:
  544             ThrowStdException("Unsupported C type for parameter array allocation");
! 545     }
  546     return 0;
  547 }
  548 
  549 template <typename ElementType>

Lines 547-556

  547 }
  548 
  549 template <typename ElementType>
  550 std::unique_ptr<ElementType[]> AllocateUniqueArray(size_t count, const char* errorMessage) {
! 551     if (count > std::numeric_limits<size_t>::max() / sizeof(ElementType)) {
! 552         ThrowStdException(errorMessage);
  553     }
  554     return std::make_unique<ElementType[]>(count);
  555 }

Lines 639-647

  639                                                   const char* errorMessage) {
  640     ReserveNativeFetchBytes(reservedBytes, count, sizeof(ElementType));
  641     return AllocateUniqueArray<ElementType>(count, errorMessage);
  642 }
! 643 
  644 std::string DescribeChar(unsigned char ch) {
  645     if (ch >= 32 && ch <= 126) {
  646         return std::string("'") + static_cast<char>(ch) + "'";
  647     } else {

Lines 682-691

  682         if (!chunk) throw py::error_already_set();
  683         py::object encoded = encoder.attr("encode")(chunk, end == length);
  684         char* data = nullptr;
  685         Py_ssize_t size = 0;
! 686         if (PyBytes_AsStringAndSize(encoded.ptr(), &data, &size) != 0) {
! 687             throw py::error_already_set();
  688         }
  689         if (size > 0) {
  690             SQLRETURN rc = put_data_fn(data, static_cast<SQLLEN>(size));
  691             if (!SQL_SUCCEEDED(rc)) return rc;

Lines 694-703

  694     if (length == 0) {
  695         py::object encoded = encoder.attr("encode")(py::str(), true);
  696         char* data = nullptr;
  697         Py_ssize_t size = 0;
! 698         if (PyBytes_AsStringAndSize(encoded.ptr(), &data, &size) != 0) {
! 699             throw py::error_already_set();
  700         }
  701         return put_data_fn(data, static_cast<SQLLEN>(size));
  702     }
  703     return SQL_SUCCESS;

Lines 712-721

  712 template <typename PutDataFn>
  713 static SQLRETURN StreamDAEParameter(const ParamInfo& info,
  714                                     const std::string& charEncoding, PutDataFn putImmutableData) {
  715     PyObject* value = info.dataPtr.ptr();
! 716     if (!value || value == Py_None) {
! 717         return putImmutableData(nullptr, 0);
  718     }
  719 
  720     if (PyUnicode_Check(value)) {
  721         if (info.paramCType == SQL_C_WCHAR) {

Lines 722-731

  722             return stream_unicode_dae_chunks(value, "utf-16-le", putImmutableData);
  723         }
  724         if (info.paramCType == SQL_C_CHAR) {
  725             return stream_unicode_dae_chunks(value, charEncoding, putImmutableData);
! 726         }
! 727         ThrowStdException("DAE only supports text C types for str values");
  728     }
  729     if (PyBytes_Check(value)) {
  730         return stream_dae_chunks(PyBytes_AS_STRING(value),
  731                                  static_cast<size_t>(PyBytes_GET_SIZE(value)),

Lines 737-746

  737         std::vector<char> chunk(std::min(static_cast<size_t>(DAE_CHUNK_SIZE), totalBytes));
  738         for (size_t offset = 0; offset < totalBytes; offset += chunk.size()) {
  739             const size_t currentSize = static_cast<size_t>(PyByteArray_GET_SIZE(value));
  740             const size_t length = std::min(chunk.size(), totalBytes - offset);
! 741             if (currentSize < offset + length) {
! 742                 ThrowStdException("bytearray changed size during DAE streaming");
  743             }
  744             std::copy_n(PyByteArray_AS_STRING(value) + offset, length, chunk.data());
  745             SQLRETURN rc = putImmutableData(chunk.data(), static_cast<SQLLEN>(length));
  746             if (!SQL_SUCCEEDED(rc)) return rc;

Lines 745-754

  745             SQLRETURN rc = putImmutableData(chunk.data(), static_cast<SQLLEN>(length));
  746             if (!SQL_SUCCEEDED(rc)) return rc;
  747         }
  748         return SQL_SUCCESS;
! 749     }
! 750     ThrowStdException("DAE only supports str, bytes, or bytearray values");
  751     return SQL_ERROR;
  752 }
  753 
  754 // Clears every parameter binding on the statement (SQL_RESET_PARAMS) and the

Lines 998-1006

   998 
   999                     if (py::isinstance<py::str>(param)) {
  1000                         // Encode Unicode string using the specified encoding
  1001                         try {
! 1002                             py::object encoded =
  1003                                 EncodeUnicodeValue(param.ptr(), charEncoding);
  1004                             encodedStr = encoded.cast<std::string>();
  1005                             LOG("BindParameters: param[%d] SQL_C_CHAR - Encoded with '%s', "
  1006                                 "size=%zu bytes",

Lines 2488-2496

  2488     }
  2489 }
  2490 
  2491 void SqlHandle::cancel() {
! 2492     clearResult();
  2493     if (is_python_finalizing()) {
  2494         return;
  2495     }
  2496     // Fetch/execute do not take this cleanup gate, so cross-thread cancellation

Lines 2729-2738

  2729     }
  2730     return errorInfo;
  2731 }
  2732 
! 2733 static std::optional<bool> AppendDiagRecords(SQLHANDLE rawHandle, SQLSMALLINT handleType,
! 2734                                            py::handle records, bool internalTruncation = false) {
  2735     bool hasTruncation = false;
  2736     // Iterate through all available diagnostic records
  2737     for (SQLSMALLINT recNumber = 1;; recNumber++) {
  2738         SQLWCHAR sqlState[6] = {0};

Lines 2777-2785

  2777         if (sqlStateUtf16 == u"01004") {
  2778             hasTruncation = true;
  2779             if (internalTruncation)
  2780                 continue;
! 2781         }
  2782         std::u16string messageUtf16 = dupeSqlWCharAsUtf16Le(
  2783             message, std::min(static_cast<size_t>(messageLen),
  2784                               static_cast<size_t>(SQL_MAX_MESSAGE_LENGTH_SQLSERVER - 1)));

Lines 2831-2839

  2831         if (FetchDiagnosticsAreEmpty(hStmt))
  2832             return false;
  2833         return AppendDiagRecords(hStmt, SQL_HANDLE_STMT, messages, internalTruncation);
  2834     }
! 2835     return std::nullopt;
  2836 }
  2837 
  2838 constexpr SQLLEN INVALID_FETCH_INDICATOR = std::numeric_limits<SQLLEN>::min();

Lines 2854-2863

  2854         if (state[0] == '0' && state[1] == '1' && state[2] == '0' && state[3] == '0' &&
  2855             state[4] == '4') {
  2856             return true;
  2857         }
! 2858     }
! 2859 }
  2860 
  2861 static bool HasDataTruncationDiagnostic(SQLHSTMT hStmt) {
  2862     return HasDataTruncationDiagnosticWithReader(hStmt, SQLGetDiagRec_ptr);
  2863 }

Lines 2996-3004

  2996 
  2997     // Run DetectParamTypes BEFORE SQLPrepare so that type-detection errors
  2998     // (unsupported type, NaN Decimal, precision overflow) don't leave the
  2999     // cursor in a half-prepared state.
! 3000     std::vector<ParamInfo> paramInfos =
  3001         DetectParamTypes(params.ptr(), input_sizes.ptr(), charEncoding);
  3002 
  3003     RETCODE rc;
  3004     bool already_prepared = is_stmt_prepared[0].cast<bool>();

Lines 3302-3310

  3302                     LOG("BindParameterArray: SQL_C_WCHAR bound - "
  3303                         "param_index=%d",
  3304                         paramIndex);
  3305                     dataPtr = wcharArray;
! 3306                     bufferLength = static_cast<SQLLEN>(bufferBytes);
  3307                     break;
  3308                 }
  3309                 case SQL_C_TINYINT:
  3310                 case SQL_C_UTINYINT: {

Lines 3374-3385

  3374                     LOG("BindParameterArray: Binding SQL_C_CHAR/BINARY array - "
  3375                         "param_index=%d, count=%zu, column_size=%zu, encoding='%s'",
  3376                         paramIndex, paramSetSize, info.columnSize, charEncoding.c_str());
  3377                     const size_t elementWidth = CheckedAddSize(
! 3378                         bufferSize, 1, "Character parameter size is too large");
! 3379                     if (elementWidth > static_cast<size_t>(std::numeric_limits<SQLLEN>::max())) {
! 3380                         ThrowStdException("Character parameter length is too large");
! 3381                     }
  3382                     char* charArray = AllocateParamBufferArray<char>(
  3383                         tempBuffers,
  3384                         CheckedMultiplySize(paramSetSize, elementWidth,
  3385                                             "Character parameter buffer is too large"));

Lines 3406-3415

  3406                                     encoded =
  3407                                         EncodeUnicodeValue(columnValues[i].ptr(), charEncoding);
  3408                                     if (PyBytes_AsStringAndSize(encoded.ptr(), &encodedData,
  3409                                                                 &encodedSize) != 0) {
! 3410                                         throw py::error_already_set();
! 3411                                     }
  3412                                     LOG("BindParameterArray: param[%d] row[%zu] SQL_C_CHAR - "
  3413                                         "Encoded with '%s', "
  3414                                         "size=%zu bytes",
  3415                                         paramIndex, i, charEncoding.c_str(),

Lines 3440-3458

  3440                                 ThrowStdException(
  3441                                     MakeParamMismatchErrorStr(info.paramCType, paramIndex));
  3442                             }
  3443 
! 3444                             const size_t dataSize = static_cast<size_t>(encodedSize);
  3445                             if (dataSize > bufferSize) {
  3446                                 LOG("BindParameterArray: String/binary too "
  3447                                     "long - param_index=%d, row=%zu, size=%zu, "
  3448                                     "max=%zu",
! 3449                                     paramIndex, i, dataSize, info.columnSize);
  3450                                 ThrowStdException("Input exceeds column size at index " +
  3451                                                   std::to_string(i));
  3452                             }
! 3453                             std::copy_n(encodedData, dataSize, charArray + i * elementWidth);
! 3454                             strLenOrIndArray[i] = static_cast<SQLLEN>(dataSize);
  3455                         }
  3456                     }
  3457                     LOG("BindParameterArray: SQL_C_CHAR/BINARY bound - "
  3458                         "param_index=%d",

Lines 3871-3881

  3871 }
  3872 
  3873 struct DaeRowBindings {
  3874     std::vector<ParamInfo> infos;
! 3875     std::vector<std::shared_ptr<void>> buffers;
! 3876 };
! 3877 
  3878 class DaeRowBindingGuard {
  3879   public:
  3880     DaeRowBindingGuard(const SqlHandlePtr& handle, const std::vector<ParamInfo>& infos)
  3881         : bindings(std::make_shared<DaeRowBindings>()), handle(handle) {

Lines 3882-3892

  3882         if (handle->retainedDaeBindings) {
  3883             const SQLRETURN rc = SQLFreeStmt_ptr(handle->get(), SQL_RESET_PARAMS);
  3884             CheckFetchError(handle, rc);
  3885             handle->retainedDaeBindings.reset();
! 3886         }
! 3887         bindings->infos = infos;
! 3888         handle->retainedDaeBindings = bindings;
  3889     }
  3890 
  3891     ~DaeRowBindingGuard() noexcept {
  3892         if (!finished) {

Lines 3891-3901

  3891     ~DaeRowBindingGuard() noexcept {
  3892         if (!finished) {
  3893             SQLRETURN cancelRc = SQL_ERROR;
  3894             SQLRETURN resetRc;
! 3895             {
! 3896                 py::gil_scoped_release release;
! 3897                 if (SQLCancel_ptr) cancelRc = SQLCancel_ptr(handle->get());
  3898                 resetRc = SQLFreeStmt_ptr(handle->get(), SQL_RESET_PARAMS);
  3899             }
  3900             if (!SQL_SUCCEEDED(cancelRc)) {
  3901                 std::fputs("mssql-python: failed to cancel abandoned DAE execution\n", stderr);

Lines 3908-3917

  3908             }
  3909         }
  3910         // Retained storage may be released by GIL-less connection cleanup.
  3911         for (auto& info : bindings->infos) {
! 3912             info.dataPtr = py::object();
! 3913         }
  3914     }
  3915 
  3916     void finish() {
  3917         const SQLRETURN rc = SQLFreeStmt_ptr(handle->get(), SQL_RESET_PARAMS);

Lines 4023-4032

  4023                 rowParams.append(values[rowIndex]);
  4024             }
  4025 
  4026             DaeRowBindingGuard rowBindings(statementHandle, paramInfos);
! 4027             auto& rowParamInfos = rowBindings.bindings->infos;
! 4028             for (size_t paramIndex = 0; paramIndex < rowParamInfos.size(); ++paramIndex) {
  4029                 if (rowParams[paramIndex].is_none()) {
  4030                     rowParamInfos[paramIndex].paramCType = SQL_C_DEFAULT;
  4031                     rowParamInfos[paramIndex].isDAE = false;
  4032                     rowParamInfos[paramIndex].dataPtr = py::none();

Lines 4063-4071

  4063                     rowParamInfos.begin(), rowParamInfos.end(),
  4064                     [token](const ParamInfo& info) { return token == &info; });
  4065                 if (matchedInfo == rowParamInfos.end()) {
  4066                     ThrowStdException(
! 4067                         "SQLExecuteMany: unrecognized paramToken from SQLParamData");
  4068                 }
  4069                 const SQLRETURN streamRc =
  4070                     StreamDAEParameter(*matchedInfo, charEncoding,
  4071                         [&](SQLPOINTER data, SQLLEN length) {

Lines 4240-4249

  4240                                  table.empty() ? 0 : SQL_NTS, scope, nullable);
  4241 }
  4242 
  4243 std::shared_ptr<PendingArrowRows> PendingRowsForNextFetch(SqlHandlePtr handle) {
! 4244     auto pending = handle->pendingArrowRows();
! 4245     if (pending) {
  4246         pending->hasSelectedRow = false;
  4247         if (pending->next == pending->count) {
  4248             handle->setPendingArrowRows(nullptr);
  4249             return nullptr;

Lines 4247-4256

  4247         if (pending->next == pending->count) {
  4248             handle->setPendingArrowRows(nullptr);
  4249             return nullptr;
  4250         }
! 4251     }
! 4252     return pending;
  4253 }
  4254 
  4255 SQLRETURN ReadSelectedArrowRow(SqlHandlePtr handle, PendingArrowRows& pending,
  4256                                 SQLUSMALLINT columnCount, py::list& row,

Lines 4266-4275

  4266         DriverLoader::getInstance().loadDriver();  // Load the driver
  4267     }
  4268     if (auto pending = PendingRowsForNextFetch(StatementHandle)) {
  4269         pending->selectedRow = pending->next++;
! 4270         pending->hasSelectedRow = true;
! 4271         return SQL_SUCCESS;
  4272     }
  4273 
  4274     // Release the GIL during the blocking ODBC call
  4275     SQLRETURN ret = SQL_ERROR;

Lines 4304-4313

  4304 }
  4305 
  4306 static py::object FetchLobColumnDataImpl(
  4307     SQLHSTMT hStmt, SQLUSMALLINT colIndex, SQLSMALLINT cType, bool isWideChar, bool isBinary,
! 4308     const std::string& charEncoding, py::handle messages, bool captureDiagnostics,
! 4309     SQLGetDataFunc getData, bool (*hasTruncationDiagnostic)(SQLHSTMT),
  4310     bool sizeWideConversion = false) {
  4311     PERF_TIMER("FetchLobColumnData");
  4312     std::vector<char> buffer;
  4313     size_t dataSize = 0;

Lines 4321-4329

  4321         // bounds UTF-16 output by two bytes per source byte, plus the terminator.
  4322         SQLLEN sourceLength = INVALID_FETCH_INDICATOR;
  4323         ret = CancellableCall(hStmt, [&] {
  4324             return getData(hStmt, colIndex, SQL_C_BINARY, nullptr, 0, &sourceLength);
! 4325         });
  4326         if (captureDiagnostics) {
  4327             CaptureFetchDiagnostics(hStmt, ret, messages, true);
  4328         }
  4329         if (!SQL_SUCCEEDED(ret)) {

Lines 4359-4367

  4359         });
  4360         std::optional<bool> capturedTruncation;
  4361         if (captureDiagnostics) {
  4362             capturedTruncation = CaptureFetchDiagnostics(hStmt, ret, messages, true);
! 4363         }
  4364 
  4365         if (ret == SQL_NO_DATA) {
  4366             if (dataSize == 0) {
  4367                 ThrowStdException("LOB fetch returned no data before making progress");

Lines 4762-4770

  4762             // 1. Detects NULL values via the indicator parameter
  4763             // 2. Initializes the variant metadata in the ODBC driver, which is required for
  4764             //    SQLColAttribute(SQL_CA_SS_VARIANT_TYPE) to return the correct underlying C type.
  4765             //    Without this probe call, SQLColAttribute returns incorrect type codes.
! 4766             SQLLEN indicator = INVALID_FETCH_INDICATOR;
  4767             {
  4768                 PERF_TIMER("sql_variant::null_probe");
  4769                 ret = CancellableGetData(hStmt, i, SQL_C_BINARY, NULL, 0, &indicator);
  4770             }

Lines 5146-5154

  5146                 SQLREAL realValue;
  5147                 SQLLEN indicator = 0;
  5148                 ret = CancellableGetData(hStmt, i, SQL_C_FLOAT, &realValue, 0, &indicator);
  5149                 CaptureFetchDiagnostics(hStmt, ret, messages);
! 5150                 ValidateDirectFetchDataLength(ret, effectiveDataType, indicator);
  5151                 if (SQL_SUCCEEDED(ret) && indicator == SQL_NULL_DATA) {
  5152                     row.append(py::none());
  5153                     break;
  5154                 }

Lines 5236-5244

  5236                 SQLDOUBLE doubleValue;
  5237                 SQLLEN indicator = 0;
  5238                 ret = CancellableGetData(hStmt, i, SQL_C_DOUBLE, &doubleValue, 0, &indicator);
  5239                 CaptureFetchDiagnostics(hStmt, ret, messages);
! 5240                 ValidateDirectFetchDataLength(ret, effectiveDataType, indicator);
  5241                 if (SQL_SUCCEEDED(ret) && indicator == SQL_NULL_DATA) {
  5242                     row.append(py::none());
  5243                     break;
  5244                 }

Lines 5775-5784

  5775             case SQL_NUMERIC:
  5776                 ResizeNativeFetchBuffer(
  5777                     buffers.charBuffers[col - 1],
  5778                     CheckedMultiplySize(fetchSize, MAX_DIGITS_IN_NUMERIC,
! 5779                                         "Native fetch buffer is too large"),
! 5780                     reservedBytes);
  5781                 ret = SQLBindCol_ptr(hStmt, col, SQL_C_CHAR, buffers.charBuffers[col - 1].data(),
  5782                                      MAX_DIGITS_IN_NUMERIC * sizeof(SQLCHAR),
  5783                                      buffers.indicators[col - 1].data());
  5784                 break;

Lines 5823-5834

  5823                 break;
  5824             case SQL_SS_UDT:
  5825             case SQL_BINARY:
  5826             case SQL_VARBINARY:
! 5827             case SQL_LONGVARBINARY: {
  5828                 // TODO: handle variable length data correctly. This logic wont
  5829                 // suffice
! 5830                 ResizeNativeFetchBuffer(buffers.charBuffers[col - 1], batchBytes, reservedBytes);
  5831                 ret = SQLBindCol_ptr(hStmt, col, SQL_C_BINARY, buffers.charBuffers[col - 1].data(),
  5832                                      bufferBytes, buffers.indicators[col - 1].data());
  5833                 break;
  5834             }

Lines 5896-5905

  5896 SQLRETURN ConvertBufferedRows(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& columnNames,
  5897                          py::list& rows, SQLUSMALLINT numCols, SQLULEN& numRowsFetched,
  5898                          const std::vector<SQLUSMALLINT>& lobColumns,
  5899                          const std::string& charEncoding = "utf-16le", int charCtype = SQL_C_WCHAR,
! 5900                          py::handle messages = {}, py::handle converters = {}, SQLULEN firstRow = 0,
! 5901                          int bufferRows = 0) {
  5902     // Pre-cache column metadata to avoid repeated dictionary lookups.
  5903     // The vectors below are consumed later by construct_rows, so they are
  5904     // declared at function scope; only the population work is wrapped in the
  5905     // cache_column_metadata timer's block (an earlier version put the timer at

Lines 5928-5937

  5928         for (SQLUSMALLINT col = 0; col < numCols; col++) {
  5929             const auto& columnMeta = GetFetchColumnMetadata(columnNames, col);
  5930             columnInfos[col].dataType = GetFetchColumnType(columnMeta);
  5931             columnInfos[col].columnSize = GetFetchColumnSize(columnMeta);
! 5932             columnInfos[col].fixedValueSize =
! 5933                 FixedFetchValueSize(columnInfos[col].dataType);
  5934             columnInfos[col].isLob =
  5935                 std::find(lobColumns.begin(), lobColumns.end(), col + 1) != lobColumns.end();
  5936             columnInfos[col].processedColumnSize = columnInfos[col].columnSize;
  5937             HandleZeroColumnSizeAtFetch(columnInfos[col].processedColumnSize);

Lines 5956-5965

  5956                     wide ? buffers.wcharBuffers[col].size() / bufferRows
  5957                          : buffers.charBuffers[col].size() / bufferRows;
  5958                 if (dt == SQL_BINARY || dt == SQL_VARBINARY ||
  5959                     dt == SQL_LONGVARBINARY || dt == SQL_SS_UDT) {
! 5960                     columnInfos[col].processedColumnSize = columnInfos[col].fetchBufferSize;
! 5961                 }
  5962             }
  5963         }
  5964 
  5965         for (SQLUSMALLINT col = 0; col < numCols; col++) {

Lines 6242-6251

  6242 
  6243 static py::list TestBoundDecimalRows(SQLSMALLINT dataType, SQLLEN indicator) {
  6244     if (dataType != SQL_DECIMAL && dataType != SQL_NUMERIC) {
  6245         throw py::value_error("Expected DECIMAL or NUMERIC");
! 6246     }
! 6247     ColumnBuffers buffers(1, 1);
  6248     buffers.charBuffers[0].assign(MAX_DIGITS_IN_NUMERIC, '0');
  6249     buffers.indicators[0][0] = indicator;
  6250     py::list columns;
  6251     columns.append(py::dict("DataType"_a = dataType, "ColumnSize"_a = 38,

Lines 6252-6261

  6252                             "ColumnName"_a = "numeric_value"));
  6253     py::list rows;
  6254     SQLULEN count = 1;
  6255     ConvertBufferedRows(nullptr, buffers, columns, rows, 1, count, {});
! 6256     return rows;
! 6257 }
  6258 
  6259 template <typename Metadata>
  6260 SQLRETURN FetchBatchData(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& columnNames,
  6261                          py::list& rows, SQLUSMALLINT numCols, SQLULEN& numRowsFetched,

Lines 6317-6326

  6317               std::vector<std::shared_ptr<void>>{storage})) {
  6318         rowsFetched = &storage->rowsFetched;
  6319         this->handle->fetchColumnsUnbound = false;
  6320     }
! 6321 
! 6322     FetchStateGuard(SqlHandlePtr handle, py::handle messages,
  6323                     const std::shared_ptr<PendingArrowRows>& pending)
  6324         : handle(std::move(handle)), messages(messages.ptr()),
  6325           lifetime(std::make_shared<FailedBindingBuffers>(
  6326               std::vector<std::shared_ptr<void>>{pending})),

Lines 6416-6424

  6416                          const std::string& charEncoding = "utf-16le",
  6417                          const std::string& wcharEncoding = "utf-16le", int charCtype = SQL_C_WCHAR,
  6418                          py::handle messages = {}, py::handle converters = {}) {
  6419     PERF_TIMER("FetchMany_wrap");
! 6420     const int fetchSize =
  6421         ValidateNativeRowCountArgument(fetchSizeArg, "Fetch size", false);
  6422     // Issue #531: upgrade SQL_C_CHAR + utf-8 to SQL_C_WCHAR on Windows so the
  6423     // driver does lossless UTF-16 conversion instead of returning ACP bytes.
  6424     charCtype = EffectiveCharCtypeForFetch(charCtype, charEncoding);

Lines 6569-6577

  6569                      PendingArrowRows* pendingRows = nullptr) {
  6570     if (getData == nullptr) {
  6571         getData = SQLGetData_ptr;
  6572     }
! 6573     size_t localStart = 0;
  6574     size_t localEnd = 0;
  6575     size_t& start = pendingRows ? pendingRows->lobStart : localStart;
  6576     size_t& end = pendingRows ? pendingRows->lobRequired : localEnd;

Lines 6595-6606

  6595         ResizeNativeFetchBuffer(dataVec, initialSize, reservedBytes);
  6596     }
  6597 
  6598     while (true) {
! 6599         if (end > dataVec.size()) {
! 6600             ResizeNativeFetchBuffer(dataVec, end, reservedBytes);
  6601         }
! 6602         if (start > dataVec.size()) {
  6603             ThrowStdException("Invalid variable-length fetch buffer offset");
  6604         }
  6605         const size_t availableBytes = CheckedMultiplySize(
  6606             dataVec.size() - start, sizeof(T), "Variable-length fetch buffer is too large");

Lines 6613-6622

  6613             static_cast<SQLLEN>(availableBytes),
  6614             &localInd); });
  6615         std::optional<bool> capturedTruncation;
  6616         if (captureDiagnostics) {
! 6617             capturedTruncation = CaptureFetchDiagnostics(hStmt, ret, messages, true);
! 6618         }
  6619 
  6620         // Indicator contents are undefined when the ODBC call fails.
  6621         if (ret == SQL_ERROR || ret == SQL_INVALID_HANDLE) {
  6622             return ret;

Lines 6936-6945

  6936         columnInfo.useWideChar = true;
  6937         columnInfo.fetchBufferSize = 2;
  6938         py::list row;
  6939         row.append(py::none());
! 6940         ColumnProcessors::ProcessWChar(row.ptr(), buffers, &columnInfo, 1, 0, nullptr);
! 6941     } else if (scenario == "odd_char_as_wchar") {
  6942         ColumnBuffers buffers(1, 1);
  6943         buffers.wcharBuffers[0].resize(2);
  6944         buffers.indicators[0][0] = 3;
  6945         ColumnInfoExt columnInfo{};

Lines 6948-6957

  6948         py::list row;
  6949         row.append(py::none());
  6950         ColumnProcessors::ProcessChar(row.ptr(), buffers, &columnInfo, 1, 0, nullptr);
  6951     } else if (scenario == "oversized_indicator") {
! 6952         std::vector<SQLCHAR> buffer(4);
! 6953         CheckedArrowSourceOffset(buffer, 0, buffer.size(), buffer.size() + 1);
  6954     } else if (scenario == "short_fixed_indicator") {
  6955         ValidateFixedFetchDataLength(SQL_INTEGER, sizeof(SQLINTEGER) - 1);
  6956     } else if (scenario == "oversized_fixed_indicator") {
  6957         ValidateFixedFetchDataLength(SQL_GUID, sizeof(SQLGUID) + 1);

Lines 6955-6964

  6955         ValidateFixedFetchDataLength(SQL_INTEGER, sizeof(SQLINTEGER) - 1);
  6956     } else if (scenario == "oversized_fixed_indicator") {
  6957         ValidateFixedFetchDataLength(SQL_GUID, sizeof(SQLGUID) + 1);
  6958     } else if (scenario == "short_direct_fixed_indicator") {
! 6959         ValidateDirectFetchDataLength(SQL_SUCCESS, SQL_TYPE_TIMESTAMP,
! 6960                                       sizeof(SQL_TIMESTAMP_STRUCT) - 1);
  6961     } else if (scenario == "oversized_direct_decimal_indicator") {
  6962         ValidateDecimalDataLength(MAX_DIGITS_IN_NUMERIC);
  6963     } else if (scenario == "zero_decimal_indicator") {
  6964         ValidateDecimalDataLength(0);

Lines 6980-6994

  6980         ValidateArrowTextPayloadLength<SQLWCHAR>(4, 4 * sizeof(SQLWCHAR));
  6981     } else if (scenario == "sql_no_total_progress") {
  6982         testGetDataResults = {
  6983             {static_cast<SQLRETURN>(SQL_SUCCESS_WITH_INFO), static_cast<SQLLEN>(SQL_NO_TOTAL)},
! 6984             {static_cast<SQLRETURN>(SQL_SUCCESS), static_cast<SQLLEN>(1)},
! 6985         };
  6986         testGetDataResultIndex = 0;
  6987 
  6988         std::vector<SQLCHAR> buffer;
! 6989         SQLLEN indicator = 0;
! 6990         size_t reservedBytes = 0;
  6991         const SQLRETURN ret = GetDataVar(nullptr, 1, SQL_C_BINARY, buffer, &indicator,
  6992                                          reservedBytes, py::none(), false, TestSQLGetData,
  6993                                          TestHasTruncationDiagnostic);
  6994         return py::make_tuple(ret, indicator, testGetDataResultIndex, buffer.size());

Lines 7022-7030

  7022             {static_cast<SQLRETURN>(SQL_SUCCESS_WITH_INFO), static_cast<SQLLEN>(5)},
  7023             {static_cast<SQLRETURN>(SQL_SUCCESS_WITH_INFO), static_cast<SQLLEN>(7)},
  7024             {static_cast<SQLRETURN>(SQL_SUCCESS_WITH_INFO),
  7025              static_cast<SQLLEN>(scenario == "exact_fit_text_chunk" ? 2 : 1)},
! 7026             {static_cast<SQLRETURN>(SQL_SUCCESS), static_cast<SQLLEN>(0)},
  7027         };
  7028         testGetDataResultIndex = 0;
  7029         std::vector<SQLCHAR> buffer;
  7030         SQLLEN indicator = INVALID_FETCH_INDICATOR;

Lines 7028-7047

  7028         testGetDataResultIndex = 0;
  7029         std::vector<SQLCHAR> buffer;
  7030         SQLLEN indicator = INVALID_FETCH_INDICATOR;
  7031         size_t reservedBytes = 0;
! 7032         const SQLRETURN ret =
! 7033             GetDataVar(nullptr, 1, SQL_C_CHAR, buffer, &indicator, reservedBytes,
! 7034                        py::none(), false, TestSQLGetData, TestHasTruncationDiagnostic);
  7035         return py::make_tuple(ret, indicator, testGetDataResultIndex, buffer.size());
  7036     } else if (scenario == "unrelated_warning_no_progress") {
! 7037         testGetDataResults = {
! 7038             {static_cast<SQLRETURN>(SQL_SUCCESS_WITH_INFO), static_cast<SQLLEN>(0)},
! 7039         };
! 7040         testGetDataResultIndex = 0;
! 7041         std::vector<SQLCHAR> buffer;
! 7042         SQLLEN indicator = 0;
! 7043         size_t reservedBytes = 0;
  7044         const SQLRETURN ret =
  7045             GetDataVar(nullptr, 1, SQL_C_BINARY, buffer, &indicator, reservedBytes,
  7046                        py::none(), false, TestSQLGetData, TestHasUnrelatedWarning);
  7047         return py::make_tuple(ret, indicator, testGetDataResultIndex, buffer.size());

Lines 7061-7107

  7061         testGetDataResults = {
  7062             {static_cast<SQLRETURN>(SQL_SUCCESS_WITH_INFO), static_cast<SQLLEN>(-2)},
  7063         };
  7064         testGetDataResultIndex = 0;
! 7065         FetchLobColumnDataImpl(nullptr, 1, SQL_C_BINARY, false, true, "", py::none(),
! 7066                                false, TestSQLGetData, TestHasTruncationDiagnostic);
! 7067     } else if (scenario == "lob_truncation_no_progress") {
! 7068         testGetDataResults = {
! 7069             {static_cast<SQLRETURN>(SQL_SUCCESS_WITH_INFO), static_cast<SQLLEN>(0)},
! 7070         };
! 7071         testGetDataResultIndex = 0;
! 7072         FetchLobColumnDataImpl(nullptr, 1, SQL_C_BINARY, false, true, "", py::none(),
! 7073                                false, TestSQLGetData, TestHasTruncationDiagnostic);
! 7074     } else if (scenario == "oversized_lob_success") {
! 7075         testGetDataResults = {
! 7076             {static_cast<SQLRETURN>(SQL_SUCCESS),
! 7077              static_cast<SQLLEN>(DAE_CHUNK_SIZE + 1)},
! 7078         };
! 7079         testGetDataResultIndex = 0;
! 7080         FetchLobColumnDataImpl(nullptr, 1, SQL_C_BINARY, false, true, "", py::none(),
! 7081                                false, TestSQLGetData, TestHasTruncationDiagnostic);
! 7082     } else if (scenario == "lob_unrelated_warning_progress") {
! 7083         testGetDataResults = {
! 7084             {static_cast<SQLRETURN>(SQL_SUCCESS_WITH_INFO), static_cast<SQLLEN>(1)},
! 7085         };
! 7086         testGetDataResultIndex = 0;
! 7087         py::bytes value =
  7088             FetchLobColumnDataImpl(nullptr, 1, SQL_C_BINARY, false, true, "",
  7089                                    py::none(), false, TestSQLGetData,
  7090                                    TestHasUnrelatedWarning)
! 7091                 .cast<py::bytes>();
! 7092         return py::make_tuple(py::len(value), testGetDataResultIndex);
! 7093     } else if (scenario == "lob_unrelated_warning_oversized") {
! 7094         testGetDataResults = {
! 7095             {static_cast<SQLRETURN>(SQL_SUCCESS_WITH_INFO),
! 7096              static_cast<SQLLEN>(DAE_CHUNK_SIZE + 1)},
! 7097         };
! 7098         testGetDataResultIndex = 0;
! 7099         FetchLobColumnDataImpl(nullptr, 1, SQL_C_BINARY, false, true, "", py::none(),
! 7100                                false, TestSQLGetData, TestHasUnrelatedWarning);
! 7101     } else if (scenario == "lob_unrelated_warning_no_total") {
! 7102         testGetDataResults = {
! 7103             {static_cast<SQLRETURN>(SQL_SUCCESS_WITH_INFO),
  7104              static_cast<SQLLEN>(SQL_NO_TOTAL)},
  7105         };
  7106         testGetDataResultIndex = 0;
  7107         FetchLobColumnDataImpl(nullptr, 1, SQL_C_BINARY, false, true, "", py::none(),

Lines 7144-7153

  7144                             TestSQLGetDataWithoutIndicator,
  7145                             TestHasTruncationDiagnostic);
  7146     } else if (scenario == "stale_indicator_reset") {
  7147         ColumnBuffers buffers(1, 2);
! 7148         buffers.indicators[0][0] = 7;
! 7149         buffers.indicators[0][1] = 9;
  7150         ResetFetchIndicators(buffers, 1);
  7151         return py::make_tuple(buffers.indicators[0][0],
  7152                               buffers.indicators[0][1]);
  7153     } else if (scenario == "diagnostic_read_failure") {

Lines 7286-7294

  7286         }
  7287     }
  7288     return ret;
  7289 }
! 7290 
  7291 int32_t days_from_civil(int y, int m, int d) {
  7292     // Implements the "days_from_civil" algorithm by Howard Hinnant
  7293     // Returns number of days since Unix epoch (1970-01-01)
  7294     y -= m <= 2;

Lines 7400-7408

  7400     const size_t offsetCount = CheckedAddSize(batchSize, 1, "Arrow batch size is too large");
  7401     const size_t initialVarDataSize =
  7402         CheckedMultiplySize(batchSize, 42, "Arrow batch size is too large");
  7403     const size_t bitmapSize =
! 7404         CheckedAddSize(batchSize, 7, "Arrow batch size is too large") / 8;
  7405     if (readerState && readerState->closed())
  7406         return SQL_NO_DATA;
  7407     // Fetch narrow char data as SQL_C_CHAR if on Linux/macOS and configured by the user
  7408     charCtype = EffectiveCharCtypeForFetch(charCtype, "utf-8");

Lines 7413-7423

  7413     if (pending) {
  7414         charCtype = pending->charCtype;
  7415     }
  7416 
! 7417     // An overly large fetch size doesn't seem to help performance.
! 7418     int fetchSize = pending ? pending->fetchSize
! 7419                            : arrowBatchSize > 0 ? std::min(arrowBatchSize, 64) : 1;
  7420 
  7421     SQLRETURN ret = SQL_ERROR;
  7422     ResultMetadataFailureGuard metadataFailure(StatementHandle->resultMetadata, ret);
  7423     SQLHSTMT hStmt = StatementHandle->get();

Lines 7490-7499

  7490             case SQL_WLONGVARCHAR:
  7491             case SQL_GUID:
  7492                 format = "U";
  7493                 arrowColumnProducer->varVal =
! 7494                     AllocateArrowArray<uint64_t>(offsetCount, reservedBytes,
! 7495                                                  "Arrow offset buffer is too large");
  7496                 EnsureNativeFetchBufferSize(arrowColumnProducer->varData, initialVarDataSize,
  7497                                         reservedBytes);
  7498                 columnVarLen[i] = true;
  7499                 // start at offset 0

Lines 7554-7562

  7554             case SQL_DOUBLE:
  7555                 format = "g";
  7556                 arrowColumnProducer->float64Val =
  7557                     AllocateArrowArray<double>(batchSize, reservedBytes,
! 7558                                                "Arrow value buffer is too large");
  7559                 arrowColumnProducer->ptrValueBuffer = arrowColumnProducer->float64Val.get();
  7560                 break;
  7561             case SQL_DECIMAL:
  7562             case SQL_NUMERIC: {

Lines 7642-7651

  7642         const size_t rowsWithinBudget = remainingBytes / rowSize;
  7643         if (rowsWithinBudget == 0) {
  7644             ThrowStdException("Native fetch buffers exceed the 256 MiB allocation limit");
  7645         }
! 7646         fetchSize = static_cast<int>(std::min<size_t>(fetchSize, rowsWithinBudget));
! 7647     }
  7648 
  7649     const int bufferFetchSize = arrowBatchSize > 0 ? fetchSize : 0;
  7650     if (!pending && bufferFetchSize > 0) {
  7651         ReserveNativeFetchBytes(

Lines 7743-7751

  7743         for (SQLULEN idxRowSql = pending->next;
  7744              idxRowSql < numRowsFetched && idxRowArrow < arrowBatchSize; idxRowSql++) {
  7745             try {
  7746                 if (hasLobColumns) {
! 7747                     for (; pending->lobColumn < numCols; ++pending->lobColumn) {
  7748                         ret = ReadArrowLobColumn(hStmt, *pending, dataTypes[pending->lobColumn],
  7749                                                   pending->lobColumn, reservedBytes, messages);
  7750                         CheckFetchError(StatementHandle, ret);
  7751                         if (!SQL_SUCCEEDED(ret)) {

Lines 7903-7916

  7903                                                                ? buffers.charBuffers[idxCol].size()
  7904                                                                : CheckedAddSize(
  7905                                                                      CheckedFetchColumnSize(
  7906                                                                          processedColumnSize),
! 7907                                                                      1,
! 7908                                                                      "Column fetch stride is too large");
  7909 #endif
  7910                             ValidateArrowTextPayloadLength<SQLCHAR>(fetchBufferSize, dataLen);
  7911                             const size_t sourceOffset = CheckedArrowSourceOffset(
! 7912                                 buffers.charBuffers[idxCol], idxRowSql, fetchBufferSize, dataLen);
  7913                             auto target_vec = &arrowColumnProducer->varData;
  7914                             auto start = arrowColumnProducer->varVal[idxRowArrow];
  7915                             if (dataLen > 0) {
  7916                                 EnsureNativeFetchBufferSize(

Lines 8331-8343

  8331     // driver does lossless UTF-16 conversion instead of returning ACP bytes.
  8332     charCtype = EffectiveCharCtypeForFetch(charCtype, charEncoding);
  8333     PendingRowsForNextFetch(StatementHandle);
  8334     SQLRETURN pendingRet = DrainPendingArrowRows(
! 8335         StatementHandle, rows, std::numeric_limits<SQLULEN>::max(), charEncoding, messages,
! 8336         converters);
! 8337     if (!SQL_SUCCEEDED(pendingRet)) {
! 8338         return pendingRet;
! 8339     }
  8340     SQLRETURN ret = SQL_ERROR;
  8341     ResultMetadataFailureGuard metadataFailure(StatementHandle->resultMetadata, ret);
  8342     SQLHSTMT hStmt = StatementHandle->get();
  8343     // Retrieve column count

mssql_python/pybind/ddbc_bindings.h

  411     }
  412     bool publishPendingArrowRows(uint64_t generation, std::shared_ptr<PendingArrowRows> rows) {
  413         std::lock_guard<std::mutex> lock(_pendingRowsMutex);
  414         if (generation != _pendingRowsGeneration) {
! 415             return false;
! 416         }
  417         _pendingArrowRows = std::move(rows);
  418         return true;
  419     }
  420     void setPendingArrowRows(std::shared_ptr<PendingArrowRows> rows) {

mssql_python/pybind/native_fetch.hpp

Lines 734-742

  734     }
  735     if (!state || plan->inputs.is_none() || !current(self, context, state, *plan, rt))
  736         return fallback(self, rt, mode, args, nargs, keywords);
  737     if (plan->handle->pendingArrowRows())
! 738         return fallback(self, rt, mode, args, nargs, keywords);
  739 
  740     if (mode == Mode::Many) {
  741         if (!single_size(*plan, args, nargs, keywords))
  742             return fallback(self, rt, mode, args, nargs, keywords);

mssql_python/pybind/param_detect.hpp

Lines 155-172

  155 inline constexpr int MAX_INLINE_BINARY = 8000;
  156 
  157 inline SQLULEN DAEColumnSize(SQLSMALLINT sqlType, SQLULEN actualSize) {
  158     switch (sqlType) {
! 159         case SQL_CHAR:
  160         case SQL_VARCHAR:
  161             return actualSize > MAX_INLINE_CHAR ? 0 : actualSize;
! 162         case SQL_WCHAR:
  163         case SQL_WVARCHAR:
  164             return actualSize > MAX_INLINE_CHAR ? 0 : actualSize;
! 165         case SQL_BINARY:
  166         case SQL_VARBINARY:
  167             return actualSize > MAX_INLINE_BINARY ? 0 : actualSize;
! 168         case SQL_LONGVARCHAR:
  169         case SQL_WLONGVARCHAR:
  170         case SQL_LONGVARBINARY:
  171             return actualSize;
  172         default:

Lines 251-266

  251         if (!chunk) throw py::error_already_set();
  252         py::object encoded = encoder.attr("encode")(chunk, end == length);
  253         const Py_ssize_t encodedSize = PyBytes_GET_SIZE(encoded.ptr());
  254         if (encodedSize > MAX_INLINE_BINARY - total) {
! 255             return MAX_INLINE_BINARY + 1;
! 256         }
  257         total += encodedSize;
  258     }
  259     if (length == 0) {
! 260         py::object encoded = encoder.attr("encode")(py::str(), true);
! 261         total = PyBytes_GET_SIZE(encoded.ptr());
! 262     }
  263     return total;
  264 }
  265 
  266 inline PyObject* FormatDecimalParam(PyObject* params, Py_ssize_t index, PyObject* value) {

Lines 289-304

  289 }
  290 
  291 inline long long ValidatedInputSizeInteger(PyObject* value, const char* fieldName) {
  292     if (!PyLong_Check(value) || PyBool_Check(value)) {
! 293         throw py::type_error(std::string(fieldName) + " must be an integer");
! 294     }
  295     int overflow = 0;
  296     const long long result = PyLong_AsLongLongAndOverflow(value, &overflow);
  297     if ((result == -1 && PyErr_Occurred()) || overflow != 0) {
! 298         PyErr_Clear();
! 299         throw py::value_error(std::string(fieldName) + " is out of range");
! 300     }
  301     return result;
  302 }
  303 
  304 inline void ValidateInputSizes(PyObject* inputSizes) {

Lines 312-321

  312     const Py_ssize_t count = PyList_GET_SIZE(inputSizes);
  313     for (Py_ssize_t index = 0; index < count; ++index) {
  314         PyObject* entry = PyList_GET_ITEM(inputSizes, index);
  315         if (entry == Py_None) {
! 316             continue;
! 317         }
  318         if (!PyTuple_Check(entry) || PyTuple_GET_SIZE(entry) != 4) {
  319             throw py::type_error("each inputSizes entry must be a four-item tuple");
  320         }

Lines 333-342

  333         if (sqlType < std::numeric_limits<SQLSMALLINT>::min() ||
  334             sqlType > std::numeric_limits<SQLSMALLINT>::max() ||
  335             cType < std::numeric_limits<SQLSMALLINT>::min() ||
  336             cType > std::numeric_limits<SQLSMALLINT>::max()) {
! 337             throw py::value_error("SQL and C types must fit in SQLSMALLINT");
! 338         }
  339         const bool isNumeric = sqlType == SQL_DECIMAL || sqlType == SQL_NUMERIC;
  340         py::int_ zero(0);
  341         const int negativeColumnSize =
  342             PyObject_RichCompareBool(columnSize, zero.ptr(), Py_LT);

Lines 342-357

  342             PyObject_RichCompareBool(columnSize, zero.ptr(), Py_LT);
  343         const int negativeDecimalDigits =
  344             PyObject_RichCompareBool(decimalDigits, zero.ptr(), Py_LT);
  345         if (negativeColumnSize == -1 || negativeDecimalDigits == -1) {
! 346             throw py::error_already_set();
! 347         }
  348         if (negativeColumnSize == 1) {
  349             throw py::value_error("column size must be non-negative");
  350         }
  351         if (negativeDecimalDigits == 1) {
! 352             throw py::value_error("decimal digits must be non-negative");
! 353         }
  354         if (!isNumeric) {
  355             const unsigned long long requestedSize = PyLong_AsUnsignedLongLong(columnSize);
  356             if (requestedSize == static_cast<unsigned long long>(-1) && PyErr_Occurred()) {
  357                 PyErr_Clear();

Lines 357-366

  357                 PyErr_Clear();
  358                 throw py::value_error("column size is out of range");
  359             }
  360             if (requestedSize > std::numeric_limits<SQLULEN>::max()) {
! 361                 throw py::value_error("column size is out of range");
! 362             }
  363             if (requestedSize > 256ULL * 1024 * 1024) {
  364                 throw py::value_error("column size exceeds the 256 MiB size-unit limit");
  365             }
  366             const unsigned long long requestedDigits =

Lines 370-379

  370                 throw py::value_error("decimal digits are out of range");
  371             }
  372             if (requestedDigits >
  373                 static_cast<unsigned long long>(std::numeric_limits<SQLSMALLINT>::max())) {
! 374                 throw py::value_error("decimal digits are out of range");
! 375             }
  376         }
  377     }
  378 }

Lines 533-542

  533                                                const std::string& charEncoding = "utf-8") {
  534     PyTypeCache::initialize();
  535 
  536     if (!PyList_Check(params)) {
! 537         throw py::type_error("params must be a list");
! 538     }
  539     ValidateInputSizes(inputSizes);
  540 
  541     const Py_ssize_t n = PyList_GET_SIZE(params);
  542     if (inputSizes != Py_None && !PyList_Check(inputSizes)) {


📋 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.vector_support.hpp: 59.5%
mssql_python.pybind.ddbc_bindings.h: 75.4%
mssql_python._native_fetch.py: 80.1%
mssql_python.pybind.row_mapping_cache.hpp: 81.5%
mssql_python.pybind.connection.connection_pool.cpp: 82.5%
mssql_python.pybind.ddbc_bindings.cpp: 83.9%
mssql_python.pybind.connection.connection.cpp: 84.2%
mssql_python.logging.py: 86.8%

🔗 Quick Links

⚙️ Build Summary 📋 Coverage Details

View Azure DevOps Build

Browse Full Coverage Report

Copilot AI review requested due to automatic review settings September 21, 2026 08:33

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.

Copilot review overview

🔵 Needs a closer look

Binary input validation must also cover array bindings consistently.

Review effort: Lite
Findings: 4 High severity · 1 Medium severity

Open (5)

@github-actions github-actions Bot added the pr-size: medium Moderate update size label Sep 21, 2026
Copilot AI review requested due to automatic review settings September 21, 2026 09:25

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.

Copilot review overview

🔵 Needs a closer look

arrow_reader() should validate batch_size before fetching the schema and performing native work.

Review effort: Lite
Findings: None

Resolved since last review (5)

Copilot AI review requested due to automatic review settings September 22, 2026 05:24

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.

Copilot review overview

🟡 Changes recommended

Critical native buffer-copy and allocation risks, plus incomplete public batch-size validation, remain unresolved.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 2 High severity

Open (2)

Comment thread mssql_python/cursor.py Resolved
Comment thread mssql_python/pybind/ddbc_bindings.cpp Resolved
Copilot AI review requested due to automatic review settings September 22, 2026 05:42
@github-actions github-actions Bot added pr-size: large Substantial code update and removed pr-size: medium Moderate update size labels Sep 22, 2026

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

A critical active finding remains: the destructor can dereference an optional null SQLCancel function pointer during DAE cleanup, causing a crash instead of preserving the original exception.

1 open issue
1 resolved since last review

Review effort: Lite

Comment thread mssql_python/pybind/ddbc_bindings.cpp Resolved
gargsaumya and others added 2 commits November 27, 2026 12:49
Restore empty-versus-NULL semantics for TVP cells and streamed Unicode/binary values. Add direct native DAE regression cases for empty text, bytes, bytearray and SQL NULL.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Always reset parameter bindings while preserving the original exception when a provider omits SQLCancel. Exercise missing-function cleanup, owner release and statement reuse in a subprocess regression.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

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

A critical active finding remains: DAE cleanup unconditionally calls the optional SQLCancel symbol, which can crash during error unwinding for drivers that do not provide it.

No open issues 🎉

1 resolved since last review

Review effort: Lite

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

Broad security-sensitive changes to native fetch, Arrow pending-row ownership, ODBC cleanup, and DAE recovery require human cross-platform runtime validation of cancellation, fault, and lifetime behavior before approval.

No open issues 🎉

Review effort: Lite

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 change still has active moderate and critical issues involving repeated per-row validation overhead and stale pending rows after statement-attribute changes.

2 open issues

Review effort: Lite

Comment thread mssql_python/pybind/ddbc_bindings.h Resolved
Comment thread mssql_python/pybind/ddbc_bindings.cpp Resolved
Compare the requested mode with the driver-reported mode in dedicated and generic setters, preserve the proven-clean pooling fast path, and check contiguous IDs across quota boundaries in both modes.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…uity

Retain per-call column references, validate lengths before the row loop, and cover exact length-check counts with real DAE execution. Preserve pending rows for metadata-only statement changes and strengthen mixed Arrow fetch regressions.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

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 the change contains an unchecked driver-reported row count that could cause out-of-bounds reads, along with misleading cancellation-error output on a supported path.

2 open issues

Review effort: Lite

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 the change has critical hidden findings affecting pool reset state, GIL-safe cleanup of retained table parameters, and complete DAE coverage for automatically detected time values.

No open issues 🎉

2 resolved since last review

Review effort: Lite

gargsaumya and others added 3 commits November 27, 2026 17:33
### Work Item / Issue Reference

> ADO Work Item:
[AB#47843](https://sqlclientdrivers.visualstudio.com/mssql-python/_workitems/edit/47843)

-------------------------------------------------------------------
### Summary

- Validate ODBC row counts, indicators, and column-buffer layout before
access.
- Check streamed fetch growth and Arrow source/destination bounds.
- Correct fixed-width buffer lengths and reject malformed wide-character
data.

Stacked on #802 so this review contains only driver-provided fetch
validation.

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Probe driver autocommit only when pending Arrow rows need a continuity decision. Keep empty setters and forced pool checkout within their existing ODBC call contracts, and exercise both setter paths and modes with stale cached state.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

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

Critical validation gaps remain for overridable binary lengths and automatically detected time values, allowing oversized payloads to bypass correct DAE classification or native-size limits.

2 open issues

Review effort: Lite

Comment thread mssql_python/cursor.py Resolved
Comment thread mssql_python/pybind/param_detect.hpp Resolved
@gargsaumya

Copy link
Copy Markdown
Contributor Author

Fixed the native pool sanitation CI regression in 78cd769, published on this PR at da685c0 (including the intervening #803 merge).

The regression came from the idempotent-autocommit fix in 92c2b29 on #802: it queried driver mode even during forced pool checkout and empty setters, changing the required ODBC call sequence from alive isolation on to alive isolation get on. The correction reads actual driver mode only when retained Arrow rows require a continuity decision. It does not trust stale cached mode or weaken the existing native call-sequence assertions.

Validation on the final combined branch:

  • Release native build passed.
  • All 101 database-free native pool sanitation scenarios passed, including four new setter/mode cases for pending-row preservation and real-mode invalidation.
  • Native binding, Arrow quota-boundary/mixed-fetch/autocommit, and SQL pooling regression selection: 145 passed, 5 skipped.
  • Pinned full-directory Black check passed.

An earlier Windows Arrow-reader subprocess timed out; that exact case passed unchanged on rerun, and the final combined selection passed cleanly. New Azure validation build 195519 is queued; this comment does not claim remote CI is already green.

Use concrete bytes and bytearray lengths for all executemany binary scans. Measure automatic time normalization in UTF-16 units and apply DAE selection after normalization. Cover binary subclass round trips and normalized time threshold boundaries.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

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

An active moderate issue remains because binary subclasses can bypass the large-value check and cause native binding failures for oversized payloads.

2 open issues

Review effort: Lite

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 a critical hidden finding indicates the new mixed ASCII/non-ASCII batch behavior can fail its added test and mis-encode data due to an inconsistent text type update.

No open issues 🎉

2 resolved since last review

Review effort: Lite

gargsaumya and others added 2 commits November 27, 2026 18:54
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Retry terminator-only zero-length truncation probes with payload space, while rejecting stalled payload reads. Reuse complete per-call diagnostic classification for continuation checks instead of querying warning records twice; preserve the reader fallback when classification is unavailable. Enable existing isolated diagnostic assertions with Windows test interposition controls.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@gargsaumya

Copy link
Copy Markdown
Contributor Author

Fixed the current build 195521 failures in d8faafe, with latest main (#924, 239f79f) merged normally.

All completed Linux x86_64 jobs had the same six test failures. These came from the fetch-size guards merged from #803 (fba5aad), not the latest binary/time review correction:

  • Narrow Arrow TEXT hit Variable-length fetch truncation made no progress on a terminator-only zero-length probe. That probe now receives one retry with payload capacity; a stalled payload read still raises.
  • All five native mixed-diagnostic modes performed a second diagnostic scan. For example, available mode produced [1,3,5,1,2] instead of [1,3,5]. Continuation checks now reuse classification from the same ODBC call's captured diagnostics. Unavailable/incomplete classification still uses the original reader fallback.

I made the existing isolated diagnostic tests runnable with Windows test-interposition controls, keeping their original call-count assertions. This reproduced all five failures locally instead of skipping them. The sixth failure was reproduced through the real native variable-length helper with the driver's zero-length truncation sequence.

After the correction:

  • All six reproductions plus the stalled-payload guard passed.
  • Broader diagnostics/native binding/parameter parity/CP1252 Arrow/native-budget selection: 619 passed, 5 skipped.
  • All 101 native pool sanitation cases passed.
  • Release build, Pylance syntax checks, and pinned full-directory Black passed.

The coverage publishing error was downstream: pytest failed before the unified coverage output was generated. No coverage bypass or weaker assertion was added. New remote CI still needs to finish; these are local validation results, not a claim that all platforms are green already.

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

Two critical issues remain: row-wise fetches can silently skip rows, and automatic text detection still sends the wrong C type for wide batch parameters.

2 open issues

Review effort: Lite

Comment thread mssql_python/cursor.py Resolved
Comment thread tests/test_023_execute_path_parity.py Resolved
Allow a payload slot after exactly filled text truncation chunks while retaining underfilled-chunk and binary no-progress validation. Reproduce the Linux CP1252-to-UTF8 fetch sequence in native tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@gargsaumya

Copy link
Copy Markdown
Contributor Author

Fixed the remaining Linux CI failure in 81dc350 (test_arrow_char_cp1252_collation_unicode[True-text]).

I reproduced the failing commit under Ubuntu/GCC with the actual Linux ODBC driver, not just a synthetic fixture. For a CP1252 value converted to UTF-8, SQLGetData returned (capacity, return, indicator) = (1, INFO, 5), (6, INFO, 7), (3, INFO, 2). That last call filled the two-byte payload exactly while still reporting truncation. The next read returns SUCCESS with indicator 0; the seven-byte UTF-8 result was already complete. The no-progress check introduced by #803 (squash fba5aad) incorrectly rejected this valid boundary. My previous d8faafe retry only covered the terminator-only empty probe and missed this nonempty converted chunk.

The fix adds one payload element when a text truncation chunk exactly fills the available payload, so completion can be confirmed while preserving the prefix. Underfilled/stalled chunks, malformed indicators, binary no-progress checks and allocation/budget guards remain enforced. Added a native regression matching the observed sequence plus underfilled-chunk rejection; the original Unicode round-trip assertion is unchanged.

Validation:

  • Real Linux failing test now passes; a read-only interposition trace confirms the extra native read returns SUCCESS/0 and all original Unicode values round-trip.
  • Windows affected suites: 519 passed, 5 skipped, 1 deselected.
  • Linux affected suites: 517 passed, 5 skipped, 1 deselected; the only two failures were cancellation probes requiring DMV visibility, which the isolated SQL login initially lacked. After temporarily granting the required performance-state visibility, the combined 53-case cancellation/CP1252/native-guard/diagnostic selection passed, including both of those probes. Temporary login and test databases were removed.
  • Release builds and native pool sanitation pass on Linux and Windows. Pinned Black and Pylance syntax checks pass.

The two new review threads were also independently checked and resolved with evidence: relative scroll preserves the expected rows after both scalar and array fetches; Python's legacy SQL_C_CHAR constant already aliases wide ODBC binding (-8), and the exact automatic-wide-binding test passes independently.

The branch includes latest main and was updated by normal push. New CI is pending; this is not a claim that the new all-platform run is already green.

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

A critical active issue causes oversized Arrow allocations before budget reduction, violating the documented batch-size behavior and triggering erroneous 256 MiB failures.

No open issues 🎉

2 resolved since last review

Review effort: Lite

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.

9 participants