From d5279be97befa371858a9b8c5c0cb428663c0c14 Mon Sep 17 00:00:00 2001 From: Jahnvi Thakkar Date: Thu, 26 Nov 2026 09:10:38 +0530 Subject: [PATCH 01/14] PERF: reduce fetchall buffer over-allocation Size bounded fetchall rowsets using checked native buffer bytes and an 8 MiB data-and-indicator target. Start with at most 100 rows and grow once while preserving existing LOB routing and encoding behavior. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 9 + mssql_python/pybind/ddbc_bindings.cpp | 283 +++++++++++--------------- tests/test_017_fetch_buffer_sizing.py | 281 +++++++++++++++++++++++++ 3 files changed, 409 insertions(+), 164 deletions(-) create mode 100644 tests/test_017_fetch_buffer_sizing.py diff --git a/CHANGELOG.md b/CHANGELOG.md index c4bcc336f..2fb33d642 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ## [Unreleased] +### Changed +- `fetchall()` starts bounded-column fetching with at most 100 rows, growing + once after a full batch to at most 1,000 rows. Batch sizing targets 8 MiB + of native column data and length/null indicators, accounting for character + conversion and terminators; a single wider row is still allowed. This is + not a limit on retained Python results or total process memory. Declared-width + string buffers and the existing LOB streaming path remain unchanged (#455, + partially addressed). + ### Added - **AB#50711:** DB-API exceptions now expose optional `native_error` metadata alongside `sqlstate` for synchronous ODBC errors. Native numbers come from the diff --git a/mssql_python/pybind/ddbc_bindings.cpp b/mssql_python/pybind/ddbc_bindings.cpp index 74be058a5..83a1b0927 100644 --- a/mssql_python/pybind/ddbc_bindings.cpp +++ b/mssql_python/pybind/ddbc_bindings.cpp @@ -4913,6 +4913,72 @@ SQLRETURN SQLFetchScroll_wrap(SqlHandlePtr StatementHandle, SQLSMALLINT FetchOri return ret; } +static size_t CheckedFetchBufferBytes(size_t count, size_t itemSize, size_t terminator = 0) { + const size_t limit = static_cast(std::numeric_limits::max()); + if (count > (limit - terminator) / itemSize) + throw std::length_error("Fetch buffer size exceeds supported limits"); + return count * itemSize + terminator; +} + +static size_t BoundColumnBufferBytes(SQLSMALLINT dataType, SQLULEN columnSize, int charCtype) { + switch (dataType) { + case SQL_CHAR: + case SQL_VARCHAR: + case SQL_LONGVARCHAR: + HandleZeroColumnSizeAtFetch(columnSize); + if (charCtype == SQL_C_WCHAR) + return CheckedFetchBufferBytes(columnSize, sizeof(SQLWCHAR), sizeof(SQLWCHAR)); +#if defined(__APPLE__) || defined(__linux__) + return CheckedFetchBufferBytes(columnSize, 4, 1); +#else + return CheckedFetchBufferBytes(columnSize, sizeof(SQLCHAR), sizeof(SQLCHAR)); +#endif + case SQL_WCHAR: + case SQL_WVARCHAR: + case SQL_WLONGVARCHAR: + HandleZeroColumnSizeAtFetch(columnSize); + return CheckedFetchBufferBytes(columnSize, sizeof(SQLWCHAR), sizeof(SQLWCHAR)); + case SQL_INTEGER: + return sizeof(SQLINTEGER); + case SQL_SMALLINT: + return sizeof(SQLSMALLINT); + case SQL_TINYINT: + case SQL_BIT: + return sizeof(SQLCHAR); + case SQL_REAL: + return sizeof(SQLREAL); + case SQL_FLOAT: + case SQL_DOUBLE: + return sizeof(SQLDOUBLE); + case SQL_DECIMAL: + case SQL_NUMERIC: + return MAX_DIGITS_IN_NUMERIC * sizeof(SQLCHAR); + case SQL_TIMESTAMP: + case SQL_TYPE_TIMESTAMP: + case SQL_DATETIME: + return sizeof(SQL_TIMESTAMP_STRUCT); + case SQL_BIGINT: + return sizeof(SQLBIGINT); + case SQL_TYPE_DATE: + return sizeof(SQL_DATE_STRUCT); + case SQL_SS_TIME2: + return sizeof(SQL_SS_TIME2_STRUCT); + case SQL_GUID: + return sizeof(SQLGUID); + case SQL_SS_UDT: + case SQL_BINARY: + case SQL_VARBINARY: + case SQL_LONGVARBINARY: + HandleZeroColumnSizeAtFetch(columnSize); + return CheckedFetchBufferBytes(columnSize, sizeof(SQLCHAR)); + case SQL_SS_TIMESTAMPOFFSET: + return sizeof(DateTimeOffset); + default: + ThrowStdException("Unsupported bound fetch data type: " + std::to_string(dataType)); + return 0; + } +} + // For column in the result set, binds a buffer to retrieve column data // TODO: Move to anonymous namespace, since it is not used outside this file template @@ -4927,31 +4993,25 @@ SQLRETURN SQLBindColums(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& const auto& columnMeta = GetFetchColumnMetadata(columnNames, col - 1); SQLSMALLINT dataType = GetFetchColumnType(columnMeta); SQLULEN columnSize = GetFetchColumnSize(columnMeta); + const size_t bufferBytes = BoundColumnBufferBytes(dataType, columnSize, charCtype); + const size_t batchBytes = CheckedFetchBufferBytes(fetchSize, bufferBytes); switch (dataType) { case SQL_CHAR: case SQL_VARCHAR: case SQL_LONGVARCHAR: { - HandleZeroColumnSizeAtFetch(columnSize); if (useWideChar) { // Bind VARCHAR columns as SQL_C_WCHAR so the ODBC driver // returns UTF-16 data, avoiding code-page decode issues. - uint64_t fetchBufferSize = columnSize + 1 /*null-terminator*/; - buffers.wcharBuffers[col - 1].resize(fetchSize * fetchBufferSize); + buffers.wcharBuffers[col - 1].resize(batchBytes / sizeof(SQLWCHAR)); ret = SQLBindCol_ptr( hStmt, col, SQL_C_WCHAR, buffers.wcharBuffers[col - 1].data(), - fetchBufferSize * sizeof(SQLWCHAR), buffers.indicators[col - 1].data()); + bufferBytes, buffers.indicators[col - 1].data()); } else { - // Original narrow-char path -#if defined(__APPLE__) || defined(__linux__) - uint64_t fetchBufferSize = columnSize * 4 + 1 /*null-terminator*/; -#else - uint64_t fetchBufferSize = columnSize + 1 /*null-terminator*/; -#endif - buffers.charBuffers[col - 1].resize(fetchSize * fetchBufferSize); + buffers.charBuffers[col - 1].resize(batchBytes); ret = SQLBindCol_ptr( hStmt, col, SQL_C_CHAR, buffers.charBuffers[col - 1].data(), - fetchBufferSize * sizeof(SQLCHAR), buffers.indicators[col - 1].data()); + bufferBytes, buffers.indicators[col - 1].data()); } break; } @@ -4960,11 +5020,9 @@ SQLRETURN SQLBindColums(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& case SQL_WLONGVARCHAR: { // TODO: handle variable length data correctly. This logic wont // suffice - HandleZeroColumnSizeAtFetch(columnSize); - uint64_t fetchBufferSize = columnSize + 1 /*null-terminator*/; - buffers.wcharBuffers[col - 1].resize(fetchSize * fetchBufferSize); + buffers.wcharBuffers[col - 1].resize(batchBytes / sizeof(SQLWCHAR)); ret = SQLBindCol_ptr(hStmt, col, SQL_C_WCHAR, buffers.wcharBuffers[col - 1].data(), - fetchBufferSize * sizeof(SQLWCHAR), + bufferBytes, buffers.indicators[col - 1].data()); break; } @@ -4996,7 +5054,7 @@ SQLRETURN SQLBindColums(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& break; case SQL_DECIMAL: case SQL_NUMERIC: - buffers.charBuffers[col - 1].resize(fetchSize * MAX_DIGITS_IN_NUMERIC); + buffers.charBuffers[col - 1].resize(batchBytes); ret = SQLBindCol_ptr(hStmt, col, SQL_C_CHAR, buffers.charBuffers[col - 1].data(), MAX_DIGITS_IN_NUMERIC * sizeof(SQLCHAR), buffers.indicators[col - 1].data()); @@ -5045,16 +5103,15 @@ SQLRETURN SQLBindColums(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& case SQL_LONGVARBINARY: // TODO: handle variable length data correctly. This logic wont // suffice - HandleZeroColumnSizeAtFetch(columnSize); - buffers.charBuffers[col - 1].resize(fetchSize * columnSize); + buffers.charBuffers[col - 1].resize(batchBytes); ret = SQLBindCol_ptr(hStmt, col, SQL_C_BINARY, buffers.charBuffers[col - 1].data(), - columnSize, buffers.indicators[col - 1].data()); + bufferBytes, buffers.indicators[col - 1].data()); break; case SQL_SS_TIMESTAMPOFFSET: buffers.datetimeoffsetBuffers[col - 1].resize(fetchSize); ret = SQLBindCol_ptr(hStmt, col, SQL_C_SS_TIMESTAMPOFFSET, buffers.datetimeoffsetBuffers[col - 1].data(), - sizeof(DateTimeOffset) * fetchSize, + bufferBytes, buffers.indicators[col - 1].data()); break; default: @@ -5141,27 +5198,15 @@ SQLRETURN FetchBatchData(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& HandleZeroColumnSizeAtFetch(columnInfos[col].processedColumnSize); SQLSMALLINT dt = columnInfos[col].dataType; - bool isCharType = (dt == SQL_CHAR || dt == SQL_VARCHAR || dt == SQL_LONGVARCHAR); - - if (isCharType && useWideChar) { - // When VARCHAR is bound as SQL_C_WCHAR, buffer size is in SQLWCHAR - // units (same as NVARCHAR). +1 for null terminator. - columnInfos[col].fetchBufferSize = columnInfos[col].processedColumnSize + 1; - } else { - // On Linux/macOS, the ODBC driver returns UTF-8 for SQL_C_CHAR where - // each character can be up to 4 bytes. Must match SQLBindColums buffer. -#if defined(__APPLE__) || defined(__linux__) - if (isCharType) { - columnInfos[col].fetchBufferSize = columnInfos[col].processedColumnSize * 4 + - 1; // *4 for UTF-8, +1 for null terminator - } else { - columnInfos[col].fetchBufferSize = - columnInfos[col].processedColumnSize + 1; // +1 for null terminator - } -#else + if (dt == SQL_CHAR || dt == SQL_VARCHAR || dt == SQL_LONGVARCHAR || + dt == SQL_WCHAR || dt == SQL_WVARCHAR || dt == SQL_WLONGVARCHAR) { + const bool wide = useWideChar || + dt == SQL_WCHAR || dt == SQL_WVARCHAR || dt == SQL_WLONGVARCHAR; columnInfos[col].fetchBufferSize = - columnInfos[col].processedColumnSize + 1; // +1 for null terminator -#endif + BoundColumnBufferBytes(dt, columnInfos[col].columnSize, charCtype) / + (wide ? sizeof(SQLWCHAR) : sizeof(SQLCHAR)); + } else { + columnInfos[col].fetchBufferSize = columnInfos[col].processedColumnSize + 1; } } @@ -5443,90 +5488,17 @@ SQLRETURN FetchBatchData(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& return ret; } -// Given a list of columns that are a part of single row in the result set, -// calculates the max size of the row -// TODO: Move to anonymous namespace, since it is not used outside this file -size_t calculateRowSize(py::list& columnNames, SQLUSMALLINT numCols) { +static size_t BoundRowBufferBytes(const py::list& columnNames, SQLUSMALLINT numCols, + int charCtype) { size_t rowSize = 0; - for (SQLUSMALLINT col = 1; col <= numCols; col++) { - auto columnMeta = columnNames[col - 1].cast(); - SQLSMALLINT dataType = columnMeta["DataType"].cast(); - SQLULEN columnSize = columnMeta["ColumnSize"].cast(); - - switch (dataType) { - case SQL_CHAR: - case SQL_VARCHAR: - case SQL_LONGVARCHAR: - rowSize += columnSize; - break; - case SQL_SS_XML: - case SQL_WCHAR: - case SQL_WVARCHAR: - case SQL_WLONGVARCHAR: - rowSize += columnSize * sizeof(SQLWCHAR); - break; - case SQL_INTEGER: - rowSize += sizeof(SQLINTEGER); - break; - case SQL_SMALLINT: - rowSize += sizeof(SQLSMALLINT); - break; - case SQL_REAL: - rowSize += sizeof(SQLREAL); - break; - case SQL_FLOAT: - rowSize += sizeof(SQLFLOAT); - break; - case SQL_DOUBLE: - rowSize += sizeof(SQLDOUBLE); - break; - case SQL_DECIMAL: - case SQL_NUMERIC: - rowSize += MAX_DIGITS_IN_NUMERIC; - break; - case SQL_TIMESTAMP: - case SQL_TYPE_TIMESTAMP: - case SQL_DATETIME: - rowSize += sizeof(SQL_TIMESTAMP_STRUCT); - break; - case SQL_BIGINT: - rowSize += sizeof(SQLBIGINT); - break; - case SQL_TYPE_DATE: - rowSize += sizeof(SQL_DATE_STRUCT); - break; - case SQL_SS_TIME2: - rowSize += sizeof(SQL_SS_TIME2_STRUCT); - break; - case SQL_GUID: - rowSize += sizeof(SQLGUID); - break; - case SQL_TINYINT: - case SQL_BIT: - rowSize += sizeof(SQLCHAR); - break; - case SQL_SS_UDT: - rowSize += (static_cast(columnSize) == SQL_NO_TOTAL || columnSize == 0) - ? SQL_MAX_LOB_SIZE - : columnSize; - break; - case SQL_BINARY: - case SQL_VARBINARY: - case SQL_LONGVARBINARY: - rowSize += columnSize; - break; - case SQL_SS_TIMESTAMPOFFSET: - rowSize += sizeof(DateTimeOffset); - break; - default: - std::string columnName = columnMeta["ColumnName"].cast(); - std::ostringstream errorString; - errorString << "Unsupported data type for column - " << columnName.c_str() - << ", Type - " << dataType << ", column ID - " << col; - LOG("calculateRowSize: %s", errorString.str().c_str()); - ThrowStdException(errorString.str()); - break; - } + const size_t limit = static_cast(std::numeric_limits::max()); + for (SQLUSMALLINT col = 0; col < numCols; ++col) { + const auto columnMeta = GetFetchColumnMetadata(columnNames, col); + const size_t bytes = BoundColumnBufferBytes( + GetFetchColumnType(columnMeta), GetFetchColumnSize(columnMeta), charCtype); + if (bytes > limit - sizeof(SQLLEN) || rowSize > limit - bytes - sizeof(SQLLEN)) + throw std::length_error("Fetch row buffer size exceeds supported limits"); + rowSize += bytes + sizeof(SQLLEN); } return rowSize; } @@ -6960,46 +6932,14 @@ SQLRETURN FetchAll_wrap(SqlHandlePtr StatementHandle, py::list& rows, return SQL_SUCCESS; } - // No LOBs detected - use binding path with batch fetching - // Define a memory limit (1 GB) - const size_t memoryLimit = 1ULL * 1024 * 1024 * 1024; - size_t totalRowSize = calculateRowSize(columnNames, numCols); - - // Calculate fetch size based on the total row size and memory limit - size_t numRowsInMemLimit; - if (totalRowSize > 0) { - numRowsInMemLimit = static_cast(memoryLimit / totalRowSize); - } else { - // Handle case where totalRowSize is 0 to avoid division by zero. - // This can happen for NVARCHAR(MAX) cols. SQLDescribeCol returns 0 - // for column size of such columns. - // TODO: Find why NVARCHAR(MAX) returns columnsize 0 - // TODO: What if a row has 2 cols, an int & NVARCHAR(MAX)? - // totalRowSize will be 4+0 = 4. It wont take NVARCHAR(MAX) - // into account. So, we will end up fetching 1000 rows at a time. - numRowsInMemLimit = 1; // fetchsize will be 10 - } - // TODO: Revisit this logic. Eventhough we're fetching fetchSize rows at a - // time, fetchall will keep all rows in memory anyway. So what are we - // gaining by fetching fetchSize rows at a time? Also, say the table has - // only 10 rows, each row size if 100 bytes. Here, we'll have fetchSize = - // 1000, so we'll allocate memory for 1000 rows inside SQLBindCol_wrap, - // while actually only need to retrieve 10 rows - int fetchSize; - if (numRowsInMemLimit == 0) { - // If the row size is larger than the memory limit, fetch one row at a - // time - fetchSize = 1; - } else if (numRowsInMemLimit > 0 && numRowsInMemLimit <= 100) { - // If between 1-100 rows fit in memoryLimit, fetch 10 rows at a time - fetchSize = 10; - } else if (numRowsInMemLimit > 100 && numRowsInMemLimit <= 1000) { - // If between 100-1000 rows fit in memoryLimit, fetch 100 rows at a time - fetchSize = 100; - } else { - fetchSize = 1000; - } - LOG("FetchAll_wrap: Fetching data in batch sizes of %d", fetchSize); + // Budget bound data and indicators, not retained Python output or allocator overhead. + // A valid row wider than the budget must still fit without truncation. + constexpr size_t bufferBudget = 8 * 1024 * 1024; + const size_t rowBytes = BoundRowBufferBytes(columnNames, numCols, charCtype); + const int maxFetchSize = static_cast( + std::max(1, std::min(1000, rowBytes ? bufferBudget / rowBytes : 1))); + int fetchSize = std::min(100, maxFetchSize); + LOG("FetchAll_wrap: Binding %d rows, %zu bytes per row", fetchSize, rowBytes); ColumnBuffers buffers(numCols, fetchSize); SQLULEN numRowsFetched = 0; @@ -7022,6 +6962,17 @@ SQLRETURN FetchAll_wrap(SqlHandlePtr StatementHandle, py::list& rows, LOG("FetchAll_wrap: Error when fetching data - SQLRETURN=%d", ret); return ret; } + if (SQL_SUCCEEDED(ret) && numRowsFetched == static_cast(fetchSize) && + fetchSize < maxFetchSize) { + // Unbind before releasing any storage still referenced by the driver. + fetchStateGuard.observe(SQLFreeStmt_ptr(hStmt, SQL_UNBIND)); + buffers = ColumnBuffers(numCols, maxFetchSize); + fetchSize = maxFetchSize; + LOG("FetchAll_wrap: Binding %d rows, %zu bytes per row", fetchSize, rowBytes); + ret = SQLBindColums(hStmt, buffers, columnNames, numCols, fetchSize, charCtype, messages); + fetchStateGuard.observe(ret); + fetchStateGuard.setRowArraySize(fetchSize); + } } fetchStateGuard.close(); @@ -7480,6 +7431,10 @@ PYBIND11_MODULE(ddbc_bindings, m) { arrowTestPointers["SQLPutData_ptr"] = reinterpret_cast(&SQLPutData_ptr); arrowTestPointers["SQLGetData_ptr"] = reinterpret_cast(&SQLGetData_ptr); arrowTestPointers["SQLFetchScroll_ptr"] = reinterpret_cast(&SQLFetchScroll_ptr); + arrowTestPointers["SQLBindCol_ptr"] = reinterpret_cast(&SQLBindCol_ptr); + arrowTestPointers["SQLDescribeCol_ptr"] = reinterpret_cast(&SQLDescribeCol_ptr); + arrowTestPointers["SQLSetStmtAttr_ptr"] = reinterpret_cast(&SQLSetStmtAttr_ptr); + arrowTestPointers["SQLFreeStmt_ptr"] = reinterpret_cast(&SQLFreeStmt_ptr); arrowTestPointers["SQLFreeHandle_ptr"] = reinterpret_cast(&SQLFreeHandle_ptr); m.attr("_arrow_test_pointer_addresses") = std::move(arrowTestPointers); #endif diff --git a/tests/test_017_fetch_buffer_sizing.py b/tests/test_017_fetch_buffer_sizing.py new file mode 100644 index 000000000..0d72b381f --- /dev/null +++ b/tests/test_017_fetch_buffer_sizing.py @@ -0,0 +1,281 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Observe live rowset bindings in isolated processes, including checked metadata.""" + +import ctypes as ct +import os +from pathlib import Path +import subprocess +import sys + +import pytest + +import mssql_python as ms +from mssql_python import ddbc_bindings + +_POINTER_NAMES = ( + "SQLBindCol_ptr", + "SQLSetStmtAttr_ptr", + "SQLFreeStmt_ptr", + "SQLFetchScroll_ptr", + "SQLDescribeCol_ptr", +) + + +@pytest.mark.parametrize( + "case", + [ + "empty", + "small", + "initial-boundary", + "growth", + "wide", + "unicode", + "narrow", + "mixed", + "zero-width", + "oversized-row", + "overflow-cell", + "overflow-row", + "growth-failure", + "unbind-failure", + "bind-failure", + "lob", + ], +) +def test_fetchall_buffer_contract(conn_str, case): + if not conn_str: + pytest.skip("DB_CONNECTION_STRING is required") + addresses = getattr(ddbc_bindings.module, "_arrow_test_pointer_addresses", {}) + if sys.platform == "win32" and not all(name in addresses for name in _POINTER_NAMES): + if os.getenv("MSSQL_ARROW_TEST_INTERPOSITION", "").upper() in ("1", "ON"): + pytest.fail("explicitly requested ODBC pointer controls are missing") + pytest.skip("requires MSSQL_ARROW_TEST_INTERPOSITION=1 on Windows") + result = subprocess.run( + [ + sys.executable, + "-c", + f"import runpy; runpy.run_path({str(Path(__file__).resolve())!r}, run_name='__main__')", + case, + ], + capture_output=True, + text=True, + timeout=120, + ) + assert result.returncode == 0, result.stdout + result.stderr + + +def _run_case(case): + addresses = getattr(ddbc_bindings.module, "_arrow_test_pointer_addresses", {}) + library = ct.CDLL(str(Path(ddbc_bindings.module.__file__).resolve())) + pointers = { + name: ( + ct.c_void_p.from_address(addresses[name]) + if name in addresses + else ct.c_void_p.in_dll(library, name) + ) + for name in _POINTER_NAMES + } + original_addresses = {} + callbacks = [] + bindings = [] + rowsets = [] + fetches = [] + events = [] + current_size = 1 + sql_len = ct.c_ssize_t + sql_ulen = ct.c_size_t + budget = 8 * 1024 * 1024 + count = {"empty": 0, "small": 3, "initial-boundary": 100}.get(case, 1207) + if case == "oversized-row": + count = 2 + if case in ("overflow-cell", "overflow-row", "lob"): + count = 3 + + def install(name, args, handler): + pointer = pointers[name] + original_addresses[name] = pointer.value + signature = ct.CFUNCTYPE(ct.c_short, *args) + original = signature(pointer.value) + callback = signature(lambda *values: handler(original, *values)) + callbacks.append(callback) + pointer.value = ct.cast(callback, ct.c_void_p).value + + def bind(original, handle, col, ctype, data, length, indicator): + bindings.append((col, ctype, length)) + events.append("bind") + if case == "bind-failure" and fetches: + return -2 + return original(handle, col, ctype, data, length, indicator) + + def attr(original, handle, attribute, value, length): + nonlocal current_size + if attribute == 27: # SQL_ATTR_ROW_ARRAY_SIZE + current_size = value + rowsets.append(value) + events.append("rowset") + if case == "growth-failure" and value > 100: + # SQL_INVALID_HANDLE has no diagnostic record; it still must surface. + return -2 + return original(handle, attribute, value, length) + + def free(original, handle, option): + if option == 2: # SQL_UNBIND + events.append("unbind") + if case == "unbind-failure" and events.count("unbind") == 1: + return -2 + return original(handle, option) + + def fetch(original, handle, orientation, offset): + fetches.append(current_size) + events.append("fetch") + return original(handle, orientation, offset) + + def describe(original, handle, col, name, capacity, actual, dtype, size, scale, nullable): + result = original(handle, col, name, capacity, actual, dtype, size, scale, nullable) + if result in (0, 1) and case == "zero-width" and col == 2: + dtype[0] = 1 + size[0] = 0 + elif result in (0, 1) and case.startswith("overflow-"): + dtype[0] = 1 # SQL_CHAR is bound, not routed through LOB streaming. + size[0] = sql_ulen(-1).value if case == "overflow-cell" else (sys.maxsize // 2) - 4 + return result + + ms.pooling(enabled=False) + with ms.connect(os.environ["DB_CONNECTION_STRING"]) as connection: + if case in ("narrow", "overflow-row"): + connection.setdecoding(ms.SQL_CHAR, encoding="cp1252", ctype=ms.SQL_CHAR) + columns = ["CAST('x' AS varchar(32))"] + expected = ["x"] + if case in ("wide", "narrow"): + columns = [ + "CAST(REPLICATE(CAST(NCHAR(233) AS nvarchar(max)), 8000) " + "COLLATE Latin1_General_100_BIN2 AS varchar(8000))" + ] * 8 + expected = ["\u00e9" * 8000] * 8 + elif case == "oversized-row": + columns = ["CAST('x' AS varchar(8000))"] * 525 + expected = ["x"] * 525 + elif case == "unicode": + columns = [ + "CAST(REPLICATE(N'x', 3998) + CAST(0x3DD842DE AS nvarchar(2)) AS nvarchar(4000))" + ] * 8 + expected = ["x" * 3998 + "\U0001f642"] * 8 + elif case == "mixed": + columns = [ + "CAST(NCHAR(233) AS varchar(8000))", + "CAST(0x3DD842DE AS nvarchar(4000))", + "CAST(NULL AS nvarchar(4000))", + "CAST(0x0001FF AS varbinary(8000))", + "CAST(12.50 AS decimal(10,2))", + "CAST('2026-01-02T03:04:05+05:30' AS datetimeoffset)", + ] + from datetime import datetime + from decimal import Decimal + + expected = [ + "\u00e9", + "\U0001f642", + None, + b"\x00\x01\xff", + Decimal("12.50"), + datetime.fromisoformat("2026-01-02T03:04:05+05:30"), + ] + elif case == "overflow-row": + columns *= 3 + expected *= 3 + elif case == "lob": + columns += ["CAST(REPLICATE(CAST(N'y' AS nvarchar(max)), 12000) AS nvarchar(max))"] + expected += ["y" * 12000] + sql = ( + "WITH d(n) AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4)," + "(5),(6),(7),(8),(9)) AS v(n)) " + f"SELECT a.n+10*b.n+100*c.n+1000*e.n AS n, {', '.join(columns)} " + "FROM d a CROSS JOIN d b CROSS JOIN d c CROSS JOIN d e " + f"WHERE a.n+10*b.n+100*c.n+1000*e.n < {count} ORDER BY n" + ) + with connection.cursor() as cursor: + cursor.execute(sql) + try: + install( + "SQLBindCol_ptr", + [ct.c_void_p, ct.c_ushort, ct.c_short, ct.c_void_p, sql_len, ct.c_void_p], + bind, + ) + install( + "SQLSetStmtAttr_ptr", + [ct.c_void_p, ct.c_int, ct.c_void_p, ct.c_int], + attr, + ) + install("SQLFreeStmt_ptr", [ct.c_void_p, ct.c_ushort], free) + install("SQLFetchScroll_ptr", [ct.c_void_p, ct.c_short, sql_len], fetch) + install( + "SQLDescribeCol_ptr", + [ + ct.c_void_p, + ct.c_ushort, + ct.c_void_p, + ct.c_short, + ct.c_void_p, + ct.POINTER(ct.c_short), + ct.POINTER(sql_ulen), + ct.c_void_p, + ct.c_void_p, + ], + describe, + ) + if case.startswith("overflow-"): + with pytest.raises(ValueError, match="Fetch .*buffer size exceeds"): + cursor.fetchall() + assert not bindings + assert not fetches + elif case.endswith("-failure"): + error = RuntimeError if case == "bind-failure" else ms.Error + with pytest.raises(error): + cursor.fetchall() + assert fetches == [100] + else: + rows = cursor.fetchall() + assert [tuple(row) for row in rows] == [(i, *expected) for i in range(count)] + assert cursor.fetchall() == [] + finally: + for name, address in original_addresses.items(): + pointers[name].value = address + + if not case.startswith("overflow-") and case != "lob" and not case.endswith("-failure"): + ncols = len(columns) + 1 + first = bindings[:ncols] + row_bytes = sum(length + ct.sizeof(sql_len) for _, _, length in first) + target = max(1, min(1000, budget // row_bytes)) + initial = min(100, target) + # An exhausted second fetchall may bind again; examine the first run. + assert rowsets[0] == initial + expected_sizes = [initial] + if count >= initial and target > initial: + expected_sizes.append(target) + first_fetch = events.index("fetch") + second_bind = events.index("bind", first_fetch + 1) + assert "unbind" in events[first_fetch + 1 : second_bind] + assert bindings[ncols : 2 * ncols] == first + assert rowsets[: len(expected_sizes)] == expected_sizes + batches = 1 if count == 0 else 2 + max(0, (count - initial + target - 1) // target) + subsequent = target if count >= initial else initial + assert fetches[:batches] == [initial] + [subsequent] * (batches - 1) + assert len(fetches) == batches + 1 + assert target * row_bytes <= budget or target == 1 + if case == "wide": + assert first[1][1:] == (-8, 16002) # SQL_C_WCHAR, including terminator. + elif case == "narrow": + width = 32001 if sys.platform != "win32" else 8001 + assert first[1][1:] == (1, width) + elif case == "oversized-row": + assert row_bytes > budget and initial == target == 1 + elif case == "lob": + assert not bindings and not fetches + cursor.execute("SELECT 42") + assert tuple(cursor.fetchone()) == (42,) + + +if __name__ == "__main__": + _run_case(sys.argv[1]) From c2e355b724e36a1a5b5e751b8968cae366db7091 Mon Sep 17 00:00:00 2001 From: Jahnvi Thakkar Date: Thu, 26 Nov 2026 09:17:50 +0530 Subject: [PATCH 02/14] TEST: distinguish row overflow from cell overflow across platforms Account for narrow-character expansion when synthesizing oversized row metadata and assert each overflow guard's exact error message. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/test_017_fetch_buffer_sizing.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/tests/test_017_fetch_buffer_sizing.py b/tests/test_017_fetch_buffer_sizing.py index 0d72b381f..5e5ce7b8b 100644 --- a/tests/test_017_fetch_buffer_sizing.py +++ b/tests/test_017_fetch_buffer_sizing.py @@ -139,7 +139,11 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, size[0] = 0 elif result in (0, 1) and case.startswith("overflow-"): dtype[0] = 1 # SQL_CHAR is bound, not routed through LOB streaming. - size[0] = sql_ulen(-1).value if case == "overflow-cell" else (sys.maxsize // 2) - 4 + if case == "overflow-cell": + size[0] = sql_ulen(-1).value + else: + expansion = 1 if sys.platform == "win32" else 4 + size[0] = (sys.maxsize // 2 - ct.sizeof(sql_len) - 1) // expansion return result ms.pooling(enabled=False) @@ -226,7 +230,12 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, describe, ) if case.startswith("overflow-"): - with pytest.raises(ValueError, match="Fetch .*buffer size exceeds"): + message = ( + "Fetch buffer size exceeds supported limits" + if case == "overflow-cell" + else "Fetch row buffer size exceeds supported limits" + ) + with pytest.raises(ValueError, match=f"^{message}$"): cursor.fetchall() assert not bindings assert not fetches From 6c2a0ed325c9d72ce8504a621947e6bee103e234 Mon Sep 17 00:00:00 2001 From: Jahnvi Thakkar Date: Thu, 26 Nov 2026 11:07:41 +0530 Subject: [PATCH 03/14] FIX: retain fetch buffers after cleanup failures Keep batch data, indicators and rows-fetched storage alive after failed ODBC cleanup, reject reuse of retired statements, and validate sizing preconditions. Add persistent-cleanup, partial-rebind and lifetime regression coverage. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 6 +- mssql_python/pybind/connection/connection.cpp | 4 +- mssql_python/pybind/ddbc_bindings.cpp | 105 +++++++++---- mssql_python/pybind/ddbc_bindings.h | 25 +++- tests/test_017_fetch_buffer_sizing.py | 141 +++++++++++++++++- 5 files changed, 240 insertions(+), 41 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2fb33d642..4a2aa90c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), conversion and terminators; a single wider row is still allowed. This is not a limit on retained Python results or total process memory. Declared-width string buffers and the existing LOB streaming path remain unchanged (#455, - partially addressed). + partially addressed). Smaller rowsets can increase driver fetch calls; these + calls do not necessarily correspond to network round trips. +- Batch fetch cleanup failures retire the statement and retain native column, + indicator, and rows-fetched storage until successful statement release or + connection disconnect, including partially rebound batches. ### Added - **AB#50711:** DB-API exceptions now expose optional `native_error` metadata diff --git a/mssql_python/pybind/connection/connection.cpp b/mssql_python/pybind/connection/connection.cpp index b4b655cdb..6f5bde0a2 100644 --- a/mssql_python/pybind/connection/connection.cpp +++ b/mssql_python/pybind/connection/connection.cpp @@ -174,10 +174,10 @@ void Connection::disconnect(bool rollbackBeforeDisconnect) { for (const auto& handle : childHandles) { handle->markImplicitlyFreed(); } - for (const auto& buffers : _cleanupState->failedParameterBuffers) { + for (const auto& buffers : _cleanupState->failedBindingBuffers) { buffers->release(); } - _cleanupState->failedParameterBuffers.clear(); + _cleanupState->failedBindingBuffers.clear(); _childStatementHandles.clear(); _allocationsSinceCompaction = 0; } diff --git a/mssql_python/pybind/ddbc_bindings.cpp b/mssql_python/pybind/ddbc_bindings.cpp index 83a1b0927..2f7ae5ed7 100644 --- a/mssql_python/pybind/ddbc_bindings.cpp +++ b/mssql_python/pybind/ddbc_bindings.cpp @@ -1714,14 +1714,14 @@ void DriverLoader::loadDriver() { } } -FailedParameterBuffers::FailedParameterBuffers(std::vector> buffers) +FailedBindingBuffers::FailedBindingBuffers(std::vector> buffers) : _buffers(std::make_unique>>(std::move(buffers))) {} -FailedParameterBuffers::~FailedParameterBuffers() { +FailedBindingBuffers::~FailedBindingBuffers() { if (_buffers) { // If even parent teardown failed, the driver may still use these addresses. // Abandon native storage to process teardown rather than free bound buffers. - std::fputs("mssql-python: retaining parameter storage after failed native teardown\n", stderr); + std::fputs("mssql-python: retaining binding storage after failed native teardown\n", stderr); _buffers.release(); } } @@ -1729,6 +1729,11 @@ FailedParameterBuffers::~FailedParameterBuffers() { // SqlHandle definition static thread_local StatementOperation* activeStatementOperation = nullptr; +class RetiredStatementError : public std::runtime_error { + public: + using std::runtime_error::runtime_error; +}; + static void RaiseStatementError(const std::string& state, const std::string& message) { py::module_::import("mssql_python.exceptions").attr("raise_exception")(state, message); } @@ -1918,17 +1923,25 @@ std::unique_lock SqlHandle::lockForCleanup() const { } SQLHANDLE SqlHandle::get() const { - return _failedParameterBuffers ? nullptr : _handle; + if (_failedBindingBuffers) { + throw RetiredStatementError( + "Statement is unavailable after failed binding cleanup; close the cursor"); + } + return _handle; } void SqlHandle::retainFailedParameters(std::vector> buffers) { - _failedParameterBuffers = std::make_shared(std::move(buffers)); + retainFailedBindings(std::make_shared(std::move(buffers))); +} + +void SqlHandle::retainFailedBindings(std::shared_ptr buffers) { + _failedBindingBuffers = std::move(buffers); py::gil_scoped_release release; auto cleanupLock = lockForCleanup(); if (!_handle || _implicitly_freed || (_cleanupState && _cleanupState->disconnected)) { - _failedParameterBuffers->release(); + _failedBindingBuffers->release(); } else if (_cleanupState) { - _cleanupState->failedParameterBuffers.push_back(_failedParameterBuffers); + _cleanupState->failedBindingBuffers.push_back(_failedBindingBuffers); } } @@ -2009,12 +2022,12 @@ SQLRETURN SqlHandle::freeHandle(ErrorInfo* error) { paramsBound = false; boundParamSignature.clear(); boundParamBuffers.clear(); - if (_failedParameterBuffers) _failedParameterBuffers->release(); + if (_failedBindingBuffers) _failedBindingBuffers->release(); } else { if (_type == SQL_HANDLE_STMT && _cleanupState) { _cleanupState->childFreeFailed = true; } - // get() hides poisoned statements; cleanup still owns their raw handle. + // get() rejects retired statements; cleanup still owns their raw handle. if (error) *error = SQLReadError(_type, _handle, ret); } return ret; @@ -4915,7 +4928,7 @@ SQLRETURN SQLFetchScroll_wrap(SqlHandlePtr StatementHandle, SQLSMALLINT FetchOri static size_t CheckedFetchBufferBytes(size_t count, size_t itemSize, size_t terminator = 0) { const size_t limit = static_cast(std::numeric_limits::max()); - if (count > (limit - terminator) / itemSize) + if (itemSize == 0 || terminator > limit || count > (limit - terminator) / itemSize) throw std::length_error("Fetch buffer size exceeds supported limits"); return count * itemSize + terminator; } @@ -5503,13 +5516,26 @@ static size_t BoundRowBufferBytes(const py::list& columnNames, SQLUSMALLINT numC return rowSize; } +struct FetchBufferState { + ColumnBuffers columns; + SQLULEN rowsFetched = 0; + + FetchBufferState(SQLSMALLINT numCols, int fetchSize) : columns(numCols, fetchSize) {} +}; + struct FetchStateGuard { SqlHandlePtr handle; PyObject* messages; // Borrowed from the enclosing native fetch call. + std::shared_ptr storage; + std::shared_ptr lifetime; int cleanupStep = 0; + bool cleanupSucceeded = true; - FetchStateGuard(SqlHandlePtr handle, py::handle messages) - : handle(std::move(handle)), messages(messages.ptr()) { + FetchStateGuard(SqlHandlePtr handle, py::handle messages, SQLSMALLINT numCols, int fetchSize) + : handle(std::move(handle)), messages(messages.ptr()), + storage(std::make_shared(numCols, fetchSize)), + lifetime(std::make_shared( + std::vector>{storage})) { this->handle->fetchColumnsUnbound = false; } @@ -5523,9 +5549,10 @@ struct FetchStateGuard { (SQLPOINTER)(intptr_t)rowArraySize, 0)); } - void configure(SQLULEN* numRowsFetched, SQLULEN rowArraySize) const { + void configure(SQLULEN rowArraySize) const { setRowArraySize(rowArraySize); - observe(SQLSetStmtAttr_ptr(handle->get(), SQL_ATTR_ROWS_FETCHED_PTR, numRowsFetched, 0)); + observe(SQLSetStmtAttr_ptr(handle->get(), SQL_ATTR_ROWS_FETCHED_PTR, + &storage->rowsFetched, 0)); } void close() { @@ -5544,6 +5571,7 @@ struct FetchStateGuard { handle->fetchColumnsUnbound = SQL_SUCCEEDED(ret); break; } + cleanupSucceeded = cleanupSucceeded && SQL_SUCCEEDED(ret); observe(ret); } } @@ -5559,6 +5587,18 @@ struct FetchStateGuard { LOG_ERROR("Fetch state cleanup failed: %s", error.what()); } } + if (cleanupSucceeded) { + lifetime->release(); + } else { + // Register native-only ownership before this guard releases its references. + // If registration itself fails, FailedBindingBuffers abandons rather than + // destroys storage that the live driver may still reference. + try { + handle->retainFailedBindings(lifetime); + } catch (const std::exception& error) { + LOG_ERROR("Failed to retain fetch storage on the connection: %s", error.what()); + } + } } }; @@ -5651,10 +5691,9 @@ SQLRETURN FetchMany_wrap(SqlHandlePtr StatementHandle, py::list& rows, int fetch return ret; } - // Initialized to 0 for LOB path counter; overwritten by ODBC in non-LOB path; - SQLULEN numRowsFetched = 0; // If we have LOBs → fall back to row-by-row fetch + SQLGetData_wrap if (!lobColumns.empty()) { + SQLULEN numRowsFetched = 0; LOG("FetchMany_wrap: LOB columns detected (%zu columns), using per-row " "SQLGetData path", lobColumns.size()); @@ -5677,8 +5716,9 @@ SQLRETURN FetchMany_wrap(SqlHandlePtr StatementHandle, py::list& rows, int fetch } // Initialize column buffers - ColumnBuffers buffers(numCols, fetchSize); - FetchStateGuard fetchStateGuard(StatementHandle, messages); + FetchStateGuard fetchStateGuard(StatementHandle, messages, numCols, fetchSize); + auto& buffers = fetchStateGuard.storage->columns; + auto& numRowsFetched = fetchStateGuard.storage->rowsFetched; // Bind columns ret = SQLBindColums(hStmt, buffers, columnNames, numCols, fetchSize, charCtype, messages); @@ -5687,7 +5727,7 @@ SQLRETURN FetchMany_wrap(SqlHandlePtr StatementHandle, py::list& rows, int fetch return ret; } - fetchStateGuard.configure(&numRowsFetched, fetchSize); + fetchStateGuard.configure(fetchSize); ret = FetchBatchData(hStmt, buffers, columnNames, rows, numCols, numRowsFetched, lobColumns, charEncoding, charCtype, messages, converters); @@ -6090,9 +6130,9 @@ SQLRETURN FetchArrowBatch_wrap(SqlHandlePtr StatementHandle, py::list& capsules, } // Initialize column buffers - ColumnBuffers buffers(numCols, fetchSize); - SQLULEN numRowsFetched = 0; - FetchStateGuard fetchStateGuard(StatementHandle, messages); + FetchStateGuard fetchStateGuard(StatementHandle, messages, numCols, fetchSize); + auto& buffers = fetchStateGuard.storage->columns; + auto& numRowsFetched = fetchStateGuard.storage->rowsFetched; if (!hasLobColumns && fetchSize > 0) { ret = SQLBindColums(hStmt, buffers, columnNames, numCols, fetchSize, charCtype, messages); @@ -6102,7 +6142,7 @@ SQLRETURN FetchArrowBatch_wrap(SqlHandlePtr StatementHandle, py::list& capsules, } } - fetchStateGuard.configure(&numRowsFetched, fetchSize); + fetchStateGuard.configure(fetchSize); int idxRowArrow = 0; @@ -6941,9 +6981,9 @@ SQLRETURN FetchAll_wrap(SqlHandlePtr StatementHandle, py::list& rows, int fetchSize = std::min(100, maxFetchSize); LOG("FetchAll_wrap: Binding %d rows, %zu bytes per row", fetchSize, rowBytes); - ColumnBuffers buffers(numCols, fetchSize); - SQLULEN numRowsFetched = 0; - FetchStateGuard fetchStateGuard(StatementHandle, messages); + FetchStateGuard fetchStateGuard(StatementHandle, messages, numCols, fetchSize); + auto& buffers = fetchStateGuard.storage->columns; + auto& numRowsFetched = fetchStateGuard.storage->rowsFetched; // Bind columns ret = SQLBindColums(hStmt, buffers, columnNames, numCols, fetchSize, charCtype, messages); @@ -6952,7 +6992,7 @@ SQLRETURN FetchAll_wrap(SqlHandlePtr StatementHandle, py::list& rows, return ret; } - fetchStateGuard.configure(&numRowsFetched, fetchSize); + fetchStateGuard.configure(fetchSize); while (ret != SQL_NO_DATA) { ret = FetchBatchData(hStmt, buffers, columnNames, rows, numCols, numRowsFetched, lobColumns, @@ -7315,6 +7355,12 @@ PYBIND11_MODULE(ddbc_bindings, m) { instance.attr("ddbc_error") = py::str(error.diagnostic.ddbcErrorMsg); instance.attr("map_sqlstate") = py::bool_(error.mapSqlState); PyErr_SetObject(type.ptr(), instance.ptr()); + } catch (const RetiredStatementError& error) { + try { + RaiseStatementError("HY010", error.what()); + } catch (py::error_already_set& pythonError) { + pythonError.restore(); + } } }); @@ -7420,6 +7466,11 @@ PYBIND11_MODULE(ddbc_bindings, m) { .def("request_close", &ArrowReaderState::requestClose); #ifdef MSSQL_ARROW_TEST_INTERPOSITION + m.def("_test_checked_fetch_buffer_bytes", &CheckedFetchBufferBytes); + m.def("_test_retained_binding_storage", [](const SqlHandlePtr& handle) { + auto storage = handle->bindingStorageForTest(); + return py::cpp_function([storage] { return !storage.expired(); }); + }); py::dict arrowTestPointers; arrowTestPointers["SQLFetch_ptr"] = reinterpret_cast(&SQLFetch_ptr); arrowTestPointers["SQLCancel_ptr"] = reinterpret_cast(&SQLCancel_ptr); diff --git a/mssql_python/pybind/ddbc_bindings.h b/mssql_python/pybind/ddbc_bindings.h index 6829903b1..736c991a6 100644 --- a/mssql_python/pybind/ddbc_bindings.h +++ b/mssql_python/pybind/ddbc_bindings.h @@ -298,11 +298,17 @@ struct DescribedParamInfo { SQLSMALLINT decimalDigits; }; -class FailedParameterBuffers { +class FailedBindingBuffers { public: - explicit FailedParameterBuffers(std::vector> buffers); - ~FailedParameterBuffers(); + explicit FailedBindingBuffers(std::vector> buffers); + ~FailedBindingBuffers(); void release() { _buffers.reset(); } +#ifdef MSSQL_ARROW_TEST_INTERPOSITION + std::weak_ptr firstBufferForTest() const { + if (_buffers && !_buffers->empty()) return _buffers->front(); + return {}; + } +#endif private: std::unique_ptr>> _buffers; @@ -329,7 +335,7 @@ struct ParamBindSignature { struct ConnectionCleanupState { std::mutex mutex; bool disconnected = false; // Protected by mutex, shared with every child. - std::vector> failedParameterBuffers; + std::vector> failedBindingBuffers; // Unlike weak_ptr expiration, this count includes destructors still freeing handles. std::atomic childStatementCount{0}; std::atomic childFreeFailed{false}; // Sticky for this physical connection. @@ -357,7 +363,14 @@ class SqlHandle { void cancel(); bool isImplicitlyFreed() const { return _implicitly_freed; } void retainFailedParameters(std::vector> buffers); + void retainFailedBindings(std::shared_ptr buffers); bool cleanupFailed() const { return _cleanupState && _cleanupState->childFreeFailed; } +#ifdef MSSQL_ARROW_TEST_INTERPOSITION + std::weak_ptr bindingStorageForTest() const { + return _failedBindingBuffers ? _failedBindingBuffers->firstBufferForTest() + : std::weak_ptr{}; + } +#endif // Mark this handle as implicitly freed (freed by parent handle) // This prevents double-free attempts when the ODBC driver automatically @@ -414,9 +427,9 @@ class SqlHandle { SQLHANDLE _handle; bool _implicitly_freed = false; // Tracks if handle was freed by parent std::shared_ptr _cleanupState; - // Only populated if both parameter reset and handle release fail. + // Native parameter or fetch storage left installed after failed cleanup. // The connection also retains this native storage if the wrapper is dropped. - std::shared_ptr _failedParameterBuffers; + std::shared_ptr _failedBindingBuffers; }; using SqlHandlePtr = std::shared_ptr; diff --git a/tests/test_017_fetch_buffer_sizing.py b/tests/test_017_fetch_buffer_sizing.py index 5e5ce7b8b..e7ada5eb2 100644 --- a/tests/test_017_fetch_buffer_sizing.py +++ b/tests/test_017_fetch_buffer_sizing.py @@ -4,6 +4,7 @@ """Observe live rowset bindings in isolated processes, including checked metadata.""" import ctypes as ct +import gc import os from pathlib import Path import subprocess @@ -20,8 +21,32 @@ "SQLFreeStmt_ptr", "SQLFetchScroll_ptr", "SQLDescribeCol_ptr", + "SQLFreeHandle_ptr", + "SQLFetch_ptr", ) +_RETAINED_CASES = ( + "persistent-unbind-failure", + "persistent-rows-fetched-failure", + "rowset-reset-failure", + "partial-bind-cleanup-failure", + "fetchmany-cleanup-failure", + "arrow-cleanup-failure", + "parent-cleanup-failure", +) + + +@pytest.mark.parametrize("item_size,terminator", [(0, 0), (1, sys.maxsize + 1)]) +def test_checked_fetch_buffer_preconditions(item_size, terminator): + checked_bytes = getattr(ddbc_bindings.module, "_test_checked_fetch_buffer_bytes", None) + if checked_bytes is None: + if os.getenv("MSSQL_ARROW_TEST_INTERPOSITION", "").upper() in ("1", "ON"): + pytest.fail("explicitly requested native sizing controls are missing") + pytest.skip("requires MSSQL_ARROW_TEST_INTERPOSITION=1") + with pytest.raises(ValueError, match="^Fetch buffer size exceeds supported limits$"): + checked_bytes(0, item_size, terminator) + assert checked_bytes(0, 1, sys.maxsize) == sys.maxsize + @pytest.mark.parametrize( "case", @@ -41,6 +66,15 @@ "growth-failure", "unbind-failure", "bind-failure", + "partial-bind-failure", + "persistent-unbind-failure", + "persistent-rows-fetched-failure", + "rowset-reset-failure", + "partial-bind-cleanup-failure", + "fetchmany-cleanup-failure", + "arrow-cleanup-failure", + "parent-cleanup-failure", + "repeat-cleanup", "lob", ], ) @@ -48,6 +82,12 @@ def test_fetchall_buffer_contract(conn_str, case): if not conn_str: pytest.skip("DB_CONNECTION_STRING is required") addresses = getattr(ddbc_bindings.module, "_arrow_test_pointer_addresses", {}) + if (case in _RETAINED_CASES or case == "repeat-cleanup") and not hasattr( + ddbc_bindings.module, "_test_retained_binding_storage" + ): + if os.getenv("MSSQL_ARROW_TEST_INTERPOSITION", "").upper() in ("1", "ON"): + pytest.fail("explicitly requested native lifetime controls are missing") + pytest.skip("native lifetime checks require MSSQL_ARROW_TEST_INTERPOSITION=1") if sys.platform == "win32" and not all(name in addresses for name in _POINTER_NAMES): if os.getenv("MSSQL_ARROW_TEST_INTERPOSITION", "").upper() in ("1", "ON"): pytest.fail("explicitly requested ODBC pointer controls are missing") @@ -84,6 +124,9 @@ def _run_case(case): fetches = [] events = [] current_size = 1 + statement = None + lifetime = None + persistent = case in _RETAINED_CASES sql_len = ct.c_ssize_t sql_ulen = ct.c_size_t budget = 8 * 1024 * 1024 @@ -103,18 +146,34 @@ def install(name, args, handler): pointer.value = ct.cast(callback, ct.c_void_p).value def bind(original, handle, col, ctype, data, length, indicator): + nonlocal statement + statement = handle bindings.append((col, ctype, length)) events.append("bind") if case == "bind-failure" and fetches: return -2 + if ( + case in ("partial-bind-failure", "partial-bind-cleanup-failure") + and fetches + and col == 2 + ): + return -2 return original(handle, col, ctype, data, length, indicator) def attr(original, handle, attribute, value, length): nonlocal current_size + if ( + case in ("persistent-rows-fetched-failure", "arrow-cleanup-failure") + and attribute == 26 + and not value + ): + return -2 # Leave SQL_ATTR_ROWS_FETCHED_PTR installed. if attribute == 27: # SQL_ATTR_ROW_ARRAY_SIZE current_size = value rowsets.append(value) events.append("rowset") + if case == "rowset-reset-failure" and value == 1: + return -2 if case == "growth-failure" and value > 100: # SQL_INVALID_HANDLE has no diagnostic record; it still must surface. return -2 @@ -125,13 +184,31 @@ def free(original, handle, option): events.append("unbind") if case == "unbind-failure" and events.count("unbind") == 1: return -2 + if case in ( + "persistent-unbind-failure", + "fetchmany-cleanup-failure", + "parent-cleanup-failure", + ): + return -2 + if case == "partial-bind-cleanup-failure" and events.count("unbind") > 1: + return -2 return original(handle, option) + def free_handle(original, kind, handle): + if case == "parent-cleanup-failure" and kind == 3 and handle == statement: + events.append("failed-free") + return -2 + return original(kind, handle) + def fetch(original, handle, orientation, offset): fetches.append(current_size) events.append("fetch") return original(handle, orientation, offset) + def arrow_fetch(original, handle): + fetches.append(current_size) + return original(handle) + def describe(original, handle, col, name, capacity, actual, dtype, size, scale, nullable): result = original(handle, col, name, capacity, actual, dtype, size, scale, nullable) if result in (0, 1) and case == "zero-width" and col == 2: @@ -213,6 +290,9 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, attr, ) install("SQLFreeStmt_ptr", [ct.c_void_p, ct.c_ushort], free) + install("SQLFreeHandle_ptr", [ct.c_short, ct.c_void_p], free_handle) + if case == "arrow-cleanup-failure": + install("SQLFetch_ptr", [ct.c_void_p], arrow_fetch) install("SQLFetchScroll_ptr", [ct.c_void_p, ct.c_short, sql_len], fetch) install( "SQLDescribeCol_ptr", @@ -240,10 +320,42 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, assert not bindings assert not fetches elif case.endswith("-failure"): - error = RuntimeError if case == "bind-failure" else ms.Error - with pytest.raises(error): - cursor.fetchall() - assert fetches == [100] + error = ( + RuntimeError + if case + in ("bind-failure", "partial-bind-failure", "partial-bind-cleanup-failure") + else ms.Error + ) + with pytest.raises(error) as failure: + if case == "fetchmany-cleanup-failure": + cursor.fetchmany(100) + elif case == "arrow-cleanup-failure": + cursor.arrow_batch(64) + else: + cursor.fetchall() + if error is RuntimeError: + assert "Failed to bind column" in str(failure.value) + if case == "arrow-cleanup-failure": + assert fetches == [64] + elif case not in ("persistent-rows-fetched-failure", "rowset-reset-failure"): + assert fetches == [100] + if case in ("partial-bind-failure", "partial-bind-cleanup-failure"): + assert bindings[3][0] == 2 + if persistent: + with pytest.raises(ms.ProgrammingError, match="failed binding cleanup"): + ddbc_bindings.DDBCSQLNumResultCols(cursor.hstmt) + with pytest.raises(ms.ProgrammingError, match="failed binding cleanup"): + cursor.fetchone() + lifetime = ddbc_bindings.module._test_retained_binding_storage(cursor.hstmt) + gc.collect() + assert lifetime(), "ODBC still holds pointers into this native storage" + if case == "parent-cleanup-failure": + cursor.close() + gc.collect() + assert "failed-free" in events + assert lifetime(), "failed statement free must retain its bound storage" + connection.close() + assert not lifetime(), "successful disconnect must release the storage" else: rows = cursor.fetchall() assert [tuple(row) for row in rows] == [(i, *expected) for i in range(count)] @@ -252,6 +364,15 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, for name, address in original_addresses.items(): pointers[name].value = address + if persistent: + cursor.close() + assert not lifetime() + if case != "parent-cleanup-failure": + with connection.cursor() as sibling: + sibling.execute("SELECT 42") + assert tuple(sibling.fetchone()) == (42,) + return + if not case.startswith("overflow-") and case != "lob" and not case.endswith("-failure"): ncols = len(columns) + 1 first = bindings[:ncols] @@ -287,4 +408,14 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, if __name__ == "__main__": - _run_case(sys.argv[1]) + if sys.argv[1] == "repeat-cleanup": + for _ in range(10): + for failure in ( + "small", + "partial-bind-failure", + "persistent-unbind-failure", + "parent-cleanup-failure", + ): + _run_case(failure) + else: + _run_case(sys.argv[1]) From 713b428631d7a48ec65ffa03a20b60d927394321 Mon Sep 17 00:00:00 2001 From: Jahnvi Thakkar Date: Thu, 26 Nov 2026 11:22:35 +0530 Subject: [PATCH 04/14] FIX: skip Arrow cleanup test without optional pyarrow Limit the dependency skip to the Arrow cleanup case so non-Arrow coverage still runs. Name the existing batch-policy bounds and express their unchanged clamp explicitly. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- mssql_python/pybind/ddbc_bindings.cpp | 11 +++++++---- tests/test_017_fetch_buffer_sizing.py | 2 ++ 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/mssql_python/pybind/ddbc_bindings.cpp b/mssql_python/pybind/ddbc_bindings.cpp index 2f7ae5ed7..59fd74108 100644 --- a/mssql_python/pybind/ddbc_bindings.cpp +++ b/mssql_python/pybind/ddbc_bindings.cpp @@ -6974,11 +6974,14 @@ SQLRETURN FetchAll_wrap(SqlHandlePtr StatementHandle, py::list& rows, // Budget bound data and indicators, not retained Python output or allocator overhead. // A valid row wider than the budget must still fit without truncation. - constexpr size_t bufferBudget = 8 * 1024 * 1024; + constexpr size_t bufferBudgetBytes = size_t{8} * 1024 * 1024; + constexpr int initialBatchRows = 100; + constexpr int maximumBatchRows = 1000; const size_t rowBytes = BoundRowBufferBytes(columnNames, numCols, charCtype); - const int maxFetchSize = static_cast( - std::max(1, std::min(1000, rowBytes ? bufferBudget / rowBytes : 1))); - int fetchSize = std::min(100, maxFetchSize); + const size_t rowsWithinBudget = rowBytes == 0 ? 1 : bufferBudgetBytes / rowBytes; + const int maxFetchSize = + static_cast(std::clamp(rowsWithinBudget, 1, maximumBatchRows)); + int fetchSize = std::min(initialBatchRows, maxFetchSize); LOG("FetchAll_wrap: Binding %d rows, %zu bytes per row", fetchSize, rowBytes); FetchStateGuard fetchStateGuard(StatementHandle, messages, numCols, fetchSize); diff --git a/tests/test_017_fetch_buffer_sizing.py b/tests/test_017_fetch_buffer_sizing.py index e7ada5eb2..c20285439 100644 --- a/tests/test_017_fetch_buffer_sizing.py +++ b/tests/test_017_fetch_buffer_sizing.py @@ -81,6 +81,8 @@ def test_checked_fetch_buffer_preconditions(item_size, terminator): def test_fetchall_buffer_contract(conn_str, case): if not conn_str: pytest.skip("DB_CONNECTION_STRING is required") + if case == "arrow-cleanup-failure": + pytest.importorskip("pyarrow") addresses = getattr(ddbc_bindings.module, "_arrow_test_pointer_addresses", {}) if (case in _RETAINED_CASES or case == "repeat-cleanup") and not hasattr( ddbc_bindings.module, "_test_retained_binding_storage" From 215e6cf34cfe4c6cbd806bc4c15d00f134607323 Mon Sep 17 00:00:00 2001 From: Jahnvi Thakkar Date: Thu, 26 Nov 2026 11:53:04 +0530 Subject: [PATCH 05/14] PERF: prototype reusable bounded-text fetch buffers Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 13 + mssql_python/pybind/ddbc_bindings.cpp | 370 +++++++++++++++++++++++++- tests/test_017_fetch_bounded_text.py | 91 ++++++- tests/test_017_fetch_buffer_sizing.py | 99 ++++++- tests/test_query_cancellation.py | 29 +- 5 files changed, 574 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 82e6594fe..678b86440 100644 --- a/README.md +++ b/README.md @@ -373,6 +373,19 @@ strings do not require a character-by-character scan. Wide-character retrieval of `VARCHAR(MAX)` values uses a non-consuming binary length probe to size the conversion buffer, avoiding character loss at truncated UTF-16 conversion boundaries while preserving embedded and trailing NULs. +The experimental bounded-text path uses ordered, unbound reads for `fetchall()` +and `fetchmany()` when a text column is wider than 256 declared characters, +reusing storage rather than allocating every cell at its declared width. +On Windows with `msodbcsql18`, short values need one read into a 512-byte starter +buffer; longer values preserve that prefix and grow reusable storage. +Up to 16 adjacent text/scalar reads share a GIL release, while retaining +per-column cancellation and diagnostic handling. Other providers/platforms and +narrow decoding retain conservative length probing. +Fixed-width and short-text result sets retain rowset batching. Wide-text result +sets still trade additional driver calls for lower temporary buffer use and can +be slower for large results; they do not change the forward-only cursor type. +Result sets containing LOB columns retain their existing streaming path. +The 256-character cutoff is provisional, not a tuned throughput threshold. Explicit `setinputsizes()` SQL types and sizes still take precedence. An explicit `VARCHAR` parameter can lose characters outside the database collation's code page even when inserting into an `NVARCHAR` destination; use `SQL_WVARCHAR` when diff --git a/mssql_python/pybind/ddbc_bindings.cpp b/mssql_python/pybind/ddbc_bindings.cpp index 59fd74108..b883b2dae 100644 --- a/mssql_python/pybind/ddbc_bindings.cpp +++ b/mssql_python/pybind/ddbc_bindings.cpp @@ -3905,6 +3905,169 @@ static inline bool CanUseSingleRowForFetchMany(SQLSMALLINT dataType, SQLULEN col } } +static size_t CheckedFetchBufferBytes(size_t count, size_t itemSize, size_t terminator); + +static bool IsBoundedFetchText(SQLSMALLINT type, SQLULEN size) { + return size > 0 && size <= SQL_MAX_LOB_SIZE && + (type == SQL_CHAR || type == SQL_VARCHAR || type == SQL_LONGVARCHAR || + type == SQL_WCHAR || type == SQL_WVARCHAR || type == SQL_WLONGVARCHAR); +} + +struct FetchTextScratch { + static constexpr size_t shortUnits = 256; + std::vector wide; + std::vector narrow; +#if defined(_WIN32) + const bool fastWideReads = GetSelectedProviderId() == kProviderMsodbcsql18; +#else + // Unix VARCHAR-to-WCHAR truncation can consume characters that did not fit. + const bool fastWideReads = false; +#endif + + SQLLEN readWideParts(const SqlHandlePtr& handle, SQLUSMALLINT column, py::handle messages, + const SQLWCHAR* first = nullptr, SQLLEN firstLength = 0) { + PERF_TIMER("FetchTextScratch::readWideParts"); + wide.resize(std::max(wide.size(), shortUnits)); + if (first) + std::copy_n(first, shortUnits, wide.data()); + bool pending = first != nullptr; + size_t used = 0; + while (true) { + const size_t available = (wide.size() - used) * sizeof(SQLWCHAR); + const size_t payload = available - sizeof(SQLWCHAR); + SQLLEN length = firstLength; + SQLRETURN ret = SQL_SUCCESS_WITH_INFO; + if (!pending) + ret = CancellableGetData(handle->get(), column, SQL_C_WCHAR, wide.data() + used, + available, &length); + pending = false; + const bool truncated = + ret == SQL_SUCCESS_WITH_INFO && + (length == SQL_NO_TOTAL || (length >= 0 && static_cast(length) > payload)); + CaptureFetchDiagnostics(handle->get(), ret, messages, truncated); + CheckFetchError(handle, ret); + if (length == SQL_NULL_DATA && SQL_SUCCEEDED(ret) && used == 0) + return SQL_NULL_DATA; + if (!SQL_SUCCEEDED(ret) || (length < 0 && !(truncated && length == SQL_NO_TOTAL)) || + (length >= 0 && length % sizeof(SQLWCHAR)) || + (!truncated && static_cast(length) > payload)) + ThrowStdException("Bounded text exceeded its probed buffer size"); + if (!truncated) + return static_cast(used * sizeof(SQLWCHAR) + length); + + const size_t prefix = used * sizeof(SQLWCHAR); + size_t bytes; + if (length == SQL_NO_TOTAL) { + bytes = CheckedFetchBufferBytes(wide.size(), sizeof(SQLWCHAR) * 2, 0); + } else { + const size_t limit = static_cast(std::numeric_limits::max()); + if (prefix > limit - sizeof(SQLWCHAR) || + static_cast(length) > limit - prefix - sizeof(SQLWCHAR)) + throw std::length_error("Fetch buffer size exceeds supported limits"); + bytes = prefix + static_cast(length) + sizeof(SQLWCHAR); + } + used += payload / sizeof(SQLWCHAR); + wide.resize(bytes / sizeof(SQLWCHAR)); + } + } + + py::object read(const SqlHandlePtr& handle, SQLUSMALLINT column, SQLSMALLINT type, + SQLULEN declaredSize, int charCtype, const std::string& encoding, + py::handle messages, py::handle converters) { + const bool unicode = type == SQL_WCHAR || type == SQL_WVARCHAR || type == SQL_WLONGVARCHAR; + const bool useWide = unicode || charCtype == SQL_C_WCHAR; + SQLLEN length = 0; + if (useWide && fastWideReads) { + length = readWideParts(handle, column, messages); + if (length == SQL_NULL_DATA) + return py::none(); + } else { + SQLLEN sourceLength = 0; + // A zero-byte binary probe does not consume nonempty text or perform a potentially + // lossy truncated VARCHAR-to-WCHAR conversion on Unix. + SQLRETURN ret = + CancellableGetData(handle->get(), column, SQL_C_BINARY, nullptr, 0, &sourceLength); + CaptureFetchDiagnostics(handle->get(), ret, messages, true); + CheckFetchError(handle, ret); + if (!SQL_SUCCEEDED(ret)) + ThrowStdException("Failed to probe bounded text length"); + if (sourceLength == SQL_NULL_DATA) + return py::none(); + if (sourceLength == SQL_NO_TOTAL) { + sourceLength = static_cast( + CheckedFetchBufferBytes(declaredSize, unicode ? sizeof(SQLWCHAR) : 1, 0)); + } else if (sourceLength < 0) { + ThrowStdException("Invalid bounded text source length"); + } + if (sourceLength == 0) { + // A successful zero-length probe already exhausts an empty value. + return decode(column, unicode, useWide, "", 0, encoding, converters); + } + size_t expansion = useWide && !unicode ? sizeof(SQLWCHAR) : 1; +#if defined(__APPLE__) || defined(__linux__) + if (!useWide) + expansion = 4; +#endif + const size_t terminator = useWide ? sizeof(SQLWCHAR) : 1; + const size_t bytes = CheckedFetchBufferBytes(sourceLength, expansion, terminator); + SQLPOINTER data; + if (useWide) { + if (bytes % sizeof(SQLWCHAR)) + ThrowStdException("Unaligned bounded UTF-16 text length"); + wide.resize(bytes / sizeof(SQLWCHAR)); + data = wide.data(); + } else { + narrow.resize(bytes); + data = narrow.data(); + } + ret = CancellableGetData(handle->get(), column, useWide ? SQL_C_WCHAR : SQL_C_CHAR, + data, static_cast(bytes), &length); + CaptureFetchDiagnostics(handle->get(), ret, messages); + CheckFetchError(handle, ret); + if (!SQL_SUCCEEDED(ret) || length < 0 || + static_cast(length) > bytes - terminator || + (useWide && length % sizeof(SQLWCHAR))) + ThrowStdException("Bounded text exceeded its probed buffer size"); + } + const auto* text = useWide ? reinterpret_cast(wide.data()) + : reinterpret_cast(narrow.data()); + return decode(column, unicode, useWide, text, length, encoding, converters); + } + + static py::object decode(SQLUSMALLINT column, bool unicode, bool useWide, + const char* text, SQLLEN length, const std::string& encoding, + py::handle converters) { + if (useWide && OutputConverters::enabled(converters, column - 1)) { + py::object converted = OutputConverters::text(text, length); + if (converted) + return converted; + } + if (!length) + return py::str(""); + PyObject* decoded; + if (unicode) + decoded = FetchText::decode_batch_utf16_native(text, length); + else if (useWide) { +#if defined(_WIN32) + decoded = PyUnicode_FromWideChar(reinterpret_cast(text), + length / sizeof(SQLWCHAR)); +#else + decoded = FetchText::decode_utf16_native(text, length); +#endif + } else { + const auto codec = GetEffectiveCharDecoding(encoding); + decoded = PyUnicode_Decode(text, length, codec.c_str(), "strict"); + } + if (!decoded) { + PyErr_Clear(); + decoded = PyBytes_FromStringAndSize(text, length); + } + if (!decoded) + throw py::error_already_set(); + return steal(decoded); + } +}; + static SQLSMALLINT FixedScalarCType(SQLSMALLINT type) { switch (type) { case SQL_INTEGER: return SQL_C_LONG; @@ -3985,13 +4148,136 @@ static size_t FetchFixedScalarRun(SQLHSTMT statement, StatementOperation* operat return read; } -static SQLRETURN GetRowData( - const SqlHandlePtr& StatementHandle, SQLUSMALLINT colCount, +static size_t FetchShortCellRun( + const SqlHandlePtr& handle, StatementOperation* operation, const ResultMetadata& metadata, + size_t first, size_t count, py::list& row, FetchTextScratch& scratch, int charCtype, + const std::string& encoding, py::handle messages, py::handle converters, SQLRETURN& result) { + if (!scratch.fastWideReads || scratch.wide.size() > FetchTextScratch::shortUnits) + return 0; + constexpr size_t capacity = 16; + std::array types; + size_t length = 0; + while (length < capacity && first + length < count) { + const auto& column = metadata.columns[first + length]; + const bool unicode = column.dataType == SQL_WCHAR || column.dataType == SQL_WVARCHAR || + column.dataType == SQL_WLONGVARCHAR; + const auto scalar = FixedScalarCType(column.dataType); + const bool text = IsBoundedFetchText(column.dataType, column.columnSize) && + (unicode || charCtype == SQL_C_WCHAR); + if (!text && !scalar) + break; + types[length] = text ? SQL_C_WCHAR : scalar; + ++length; + } + if (length < 2) + return 0; + + struct Cell { + std::array data; + SQLINTEGER integer; + SQLSMALLINT smallInteger; + SQLBIGINT big; + SQLREAL real; + SQLDOUBLE floating; + SQLLEN indicator = 0; + SQLPOINTER buffer(SQLSMALLINT type) { + switch (type) { + case SQL_C_LONG: return &integer; + case SQL_C_SHORT: return &smallInteger; + case SQL_C_SBIGINT: return &big; + case SQL_C_FLOAT: return ℜ + case SQL_C_DOUBLE: return &floating; + default: return data.data(); + } + } + }; + std::array cells; + constexpr size_t payload = (FetchTextScratch::shortUnits - 1) * sizeof(SQLWCHAR); + SQLHSTMT statement = handle->get(); + size_t read = 0; + bool admitted = true; + PERF_TIMER("SQLGetData::short_cell_group"); + { + py::gil_scoped_release release; + for (; read < length;) { + auto& cell = cells[read]; + const auto type = types[read]; + result = CancellableCallWithoutGIL( + operation, + [&] { + return SQLGetData_ptr(statement, static_cast(first + read + 1), + type, cell.buffer(type), sizeof(cell.data), + &cell.indicator); + }, + admitted); + ++read; + // Stop before another call overwrites diagnostics or consumes later + // columns after an invalid length. Each read retains its cancellation fence. + if (result != SQL_SUCCESS || + (cell.indicator != SQL_NULL_DATA && + (cell.indicator < 0 || static_cast(cell.indicator) > payload || + cell.indicator % sizeof(SQLWCHAR)))) + break; + } + } + result = operation->checkResult(statement, result, admitted); + const auto& last = cells[read - 1]; + const bool truncated = types[read - 1] == SQL_C_WCHAR && result == SQL_SUCCESS_WITH_INFO && + (last.indicator == SQL_NO_TOTAL || + (last.indicator >= 0 && static_cast(last.indicator) > payload)); + if (!truncated) + CaptureFetchDiagnostics(statement, result, messages); + if (result == SQL_NO_DATA) + ThrowStdException("Bounded text exceeded its probed buffer size"); + if (!SQL_SUCCEEDED(result)) + return read; + + for (size_t index = 0; index < read; ++index) { + const auto& cell = cells[index]; + if (cell.indicator == SQL_NULL_DATA) { + row.append(py::none()); + continue; + } + const auto column = static_cast(first + index + 1); + if (types[index] != SQL_C_WCHAR) { + if (cell.indicator < 0 || static_cast(cell.indicator) > payload) + ThrowStdException("Invalid bounded scalar length"); + switch (types[index]) { + case SQL_C_LONG: row.append(static_cast(cell.integer)); break; + case SQL_C_SHORT: row.append(static_cast(cell.smallInteger)); break; + case SQL_C_SBIGINT: row.append(static_cast(cell.big)); break; + case SQL_C_FLOAT: row.append(cell.real); break; + default: row.append(cell.floating); break; + } + continue; + } + const bool unicode = metadata.columns[first + index].dataType == SQL_WCHAR || + metadata.columns[first + index].dataType == SQL_WVARCHAR || + metadata.columns[first + index].dataType == SQL_WLONGVARCHAR; + if (truncated && index + 1 == read) { + const auto bytes = + scratch.readWideParts(handle, column, messages, cell.data.data(), cell.indicator); + row.append(FetchTextScratch::decode(column, unicode, true, + reinterpret_cast(scratch.wide.data()), + bytes, encoding, converters)); + } else { + if (cell.indicator < 0 || static_cast(cell.indicator) > payload || + cell.indicator % sizeof(SQLWCHAR)) + ThrowStdException("Bounded text exceeded its probed buffer size"); + row.append(FetchTextScratch::decode(column, unicode, true, + reinterpret_cast(cell.data.data()), + cell.indicator, encoding, converters)); + } + } + return read; +} + +static SQLRETURN GetRowData(const SqlHandlePtr& StatementHandle, SQLUSMALLINT colCount, py::list& row, const std::string& charEncoding, - const std::string& wcharEncoding, int charCtype, - py::handle messages, const ResultMetadataCache::Snapshot& snapshot, + const std::string& wcharEncoding, int charCtype, py::handle messages, + const ResultMetadataCache::Snapshot& snapshot, bool completeResult = false, py::handle converters = {}, - bool batchText = false) { + bool batchText = false, FetchTextScratch* textScratch = nullptr) { PERF_TIMER("SQLGetData_wrap"); // Note: wcharEncoding parameter is reserved for future use // Currently WCHAR data always uses UTF-16LE for Windows compatibility @@ -4019,10 +4305,22 @@ static SQLRETURN GetRowData( } auto* operation = StatementOperation::current(hStmt); - const bool groupScalars = operation && metadata && + const bool groupScalars = + operation && metadata && (!converters || converters.is_none() || (PyDict_CheckExact(converters.ptr()) && PyDict_Size(converters.ptr()) == 0)); for (SQLSMALLINT i = 1; i <= colCount; ++i) { + if (textScratch && operation && metadata) { + const auto read = FetchShortCellRun( + StatementHandle, operation, *metadata, static_cast(i - 1), colCount, + row, *textScratch, charCtype, charEncoding, messages, converters, ret); + if (read) { + if (!SQL_SUCCEEDED(ret)) + return ret; + i += static_cast(read - 1); + continue; + } + } if (groupScalars) { const auto read = FetchFixedScalarRun(hStmt, operation, *metadata, static_cast(i - 1), colCount, @@ -4136,6 +4434,11 @@ static SQLRETURN GetRowData( (long)variantCType, effectiveDataType); } + if (textScratch && IsBoundedFetchText(dataType, columnSize)) { + row.append(textScratch->read(StatementHandle, i, dataType, columnSize, charCtype, + charEncoding, messages, converters)); + continue; + } switch (effectiveDataType) { case SQL_CHAR: case SQL_VARCHAR: @@ -5602,6 +5905,44 @@ struct FetchStateGuard { } }; +// SQL_GD_BLOCK does not permit SQLGetData on multirow forward-only cursors. +// Keep every column unbound and read in order; no driver pointers outlive a call. +static SQLRETURN FetchDynamicTextRows( + const SqlHandlePtr& handle, SQLUSMALLINT numCols, py::list& rows, size_t limit, + const std::string& charEncoding, const std::string& wcharEncoding, int charCtype, + py::handle messages, py::handle converters) { + PERF_TIMER("FetchDynamicTextRows"); + if (!handle->fetchColumnsUnbound) { + SQLRETURN ret = SQLFreeStmt_ptr(handle->get(), SQL_UNBIND); + CaptureFetchDiagnostics(handle->get(), ret, messages); + CheckFetchError(handle, ret); + if (!SQL_SUCCEEDED(ret)) + return ret; + handle->fetchColumnsUnbound = true; + } + FetchTextScratch scratch; + for (size_t count = 0; count < limit; ++count) { + SQLRETURN ret = CancellableCall(handle->get(), [&] { + return SQLFetch_ptr(handle->get()); + }); + CaptureFetchDiagnostics(handle->get(), ret, messages); + CheckFetchError(handle, ret); + if (ret == SQL_NO_DATA) + break; + if (!SQL_SUCCEEDED(ret)) + return ret; + py::list row; + ret = GetRowData(handle, numCols, row, charEncoding, wcharEncoding, charCtype, + messages, handle->resultMetadata.snapshot(), true, converters, + true, &scratch); + CheckFetchError(handle, ret); + if (!SQL_SUCCEEDED(ret)) + return ret; + rows.append(row); + } + return SQL_SUCCESS; +} + // FetchMany_wrap - Fetches multiple rows of data from the result set. // // @param StatementHandle: Handle to the statement from which data is to be @@ -5673,6 +6014,7 @@ SQLRETURN FetchMany_wrap(SqlHandlePtr StatementHandle, py::list& rows, int fetch std::vector lobColumns; bool singleRowEligible = fetchSize == 1; + bool dynamicText = false; for (SQLSMALLINT i = 0; i < numCols; i++) { const auto& column = columnNames.at(i); if (IsLobOrVariantColumn(column.dataType, column.columnSize)) { @@ -5680,8 +6022,15 @@ SQLRETURN FetchMany_wrap(SqlHandlePtr StatementHandle, py::list& rows, int fetch } singleRowEligible = singleRowEligible && CanUseSingleRowForFetchMany(column.dataType, column.columnSize); + dynamicText = dynamicText || + (IsBoundedFetchText(column.dataType, column.columnSize) && + column.columnSize > 256); } + if (dynamicText && lobColumns.empty()) + return FetchDynamicTextRows(StatementHandle, numCols, rows, fetchSize, + charEncoding, wcharEncoding, charCtype, messages, converters); + if (singleRowEligible) { py::list row; ret = FetchSingleRow(StatementHandle, row, charEncoding, wcharEncoding, charCtype, messages, @@ -6920,6 +7269,7 @@ SQLRETURN FetchAll_wrap(SqlHandlePtr StatementHandle, py::list& rows, } std::vector lobColumns; + bool dynamicText = false; for (SQLSMALLINT i = 0; i < numCols; i++) { auto colMeta = columnNames[i].cast(); SQLSMALLINT dataType = colMeta["DataType"].cast(); @@ -6930,10 +7280,12 @@ SQLRETURN FetchAll_wrap(SqlHandlePtr StatementHandle, py::list& rows, if (IsLobOrVariantColumn(dataType, columnSize)) { lobColumns.push_back(i + 1); // 1-based } + dynamicText = dynamicText || + (IsBoundedFetchText(dataType, columnSize) && columnSize > 256); } // If we have LOBs → fall back to row-by-row fetch + SQLGetData_wrap - if (!lobColumns.empty()) { + if (!lobColumns.empty() || dynamicText) { LOG("FetchAll_wrap: LOB columns detected (%zu columns), using per-row " "SQLGetData path", lobColumns.size()); @@ -6955,6 +7307,10 @@ SQLRETURN FetchAll_wrap(SqlHandlePtr StatementHandle, py::list& rows, type == SQL_SS_VARIANT ? 0 : column["ColumnSize"].cast()}); } StatementHandle->resultMetadata.publish(metadataSnapshot.generation, std::move(metadata)); + if (lobColumns.empty()) + return FetchDynamicTextRows( + StatementHandle, numCols, rows, std::numeric_limits::max(), + charEncoding, wcharEncoding, charCtype, messages, converters); while (true) { ret = CancellableCall(hStmt, [&] { return SQLFetch_ptr(hStmt); }); CaptureFetchDiagnostics(hStmt, ret, messages); diff --git a/tests/test_017_fetch_bounded_text.py b/tests/test_017_fetch_bounded_text.py index 38845af54..e76d17c10 100644 --- a/tests/test_017_fetch_bounded_text.py +++ b/tests/test_017_fetch_bounded_text.py @@ -219,9 +219,10 @@ def test_bounded_nvarchar_strict_decode_error(db_connection, raw, method, forced ], ids=["explicit-cold", "explicit-warm", "default-cold", "default-warm", "batch", "all"], ) -def test_bounded_nvarchar_batch_malformed_fallback(db_connection, raw, method, warmed): +@pytest.mark.parametrize("width", [64, 4000]) +def test_bounded_nvarchar_batch_malformed_fallback(db_connection, raw, method, warmed, width): """Preserve the existing platform-specific batch behavior for unpaired surrogates.""" - expression = f"CAST(0x{raw} AS nvarchar(64))" + expression = f"CAST(0x{raw} AS nvarchar({width}))" raw_bytes = bytes.fromhex(raw) with db_connection.cursor() as cursor: cursor.execute(f"SELECT DATALENGTH({expression}), CAST({expression} AS varbinary(64))") @@ -261,3 +262,89 @@ def test_bounded_nvarchar_batch_malformed_fallback(db_connection, raw, method, w assert cursor.fetchone() is None cursor.execute("SELECT CAST(N'recovered' AS nvarchar(64))") assert cursor.fetchone()[0] == "recovered" + + +@pytest.mark.parametrize("method", ["fetchall", "fetchmany", "interleave"]) +@pytest.mark.parametrize("converted", [False, True]) +def test_wide_bounded_text_actual_lengths(db_connection, method, converted): + payloads = [None, "", "\ufeffA\0B\ufffe", "A\U0001f642Z", "x" * 3998 + "\U0001f642"] + cases = " ".join( + f"WHEN {i} THEN " + + ( + "NULL" + if value is None + else f"CAST(0x{value.encode('utf-16le').hex()} AS nvarchar(4000))" + ) + for i, value in enumerate(payloads) + ) + observed = [] + if converted: + db_connection.add_output_converter( + str, lambda raw: observed.append(raw) or raw.decode("utf-16le") + "!" + ) + db_connection.add_output_converter(int, lambda value: value + 10000) + try: + with db_connection.cursor() as cursor: + cursor.execute( + "WITH d(n) AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4)," + "(5),(6),(7),(8),(9)) AS v(n)) " + f"SELECT n, CAST(CASE n % 5 {cases} END AS nvarchar(4000)), " + "CAST(NCHAR(233) COLLATE Latin1_General_100_BIN2 AS varchar(8000)), " + "CAST(0x0001FF AS varbinary(8)), CAST(n AS decimal(10,2)) " + "FROM (SELECT a.n+10*b.n+100*c.n AS n FROM d a CROSS JOIN d b CROSS JOIN d c) v " + "WHERE n < 207 ORDER BY n" + ) + actual = [] + if method == "interleave": + actual.append(cursor.fetchone()) + if method == "fetchall": + actual.extend(cursor.fetchall()) + else: + while batch := cursor.fetchmany(7): + actual.extend(batch) + assert [(row[0], row[1], row[2], row[3], int(row[4])) for row in actual] == [ + ( + n + (10000 if converted else 0), + ( + None + if payloads[n % 5] is None + else payloads[n % 5] + ("!" if converted else "") + ), + "\u00e9" + ("!" if converted else ""), + b"\0\x01\xff", + n, + ) + for n in range(207) + ] + assert cursor.fetchone() is None + assert cursor.fetchall() == [] + if converted: + assert observed == [ + value.encode("utf-16le") + for n in range(207) + for value in (payloads[n % 5], "\u00e9") + if value is not None + ] + finally: + if converted: + db_connection.remove_output_converter(str) + db_connection.remove_output_converter(int) + + +@pytest.mark.parametrize("method", ["fetchall", "fetchmany"]) +@pytest.mark.parametrize("sqltype", ["nvarchar(4000)", "varchar(8000)"]) +@pytest.mark.parametrize("offset", [253, 254, 255, 256, 511]) +def test_wide_text_continuation_boundaries(db_connection, utf8_collation, method, sqltype, offset): + payload = "a" * offset + "\U0001f642" + "\0" + "\u00e9\u20ac" + "z" * 550 + expected = ["before", payload, "after"] + values = ", ".join( + f"({i}, CAST(CAST(0x{value.encode('utf-16le').hex()} AS nvarchar(4000)) " + f"COLLATE {utf8_collation} AS {sqltype}))" + for i, value in enumerate(expected) + ) + with db_connection.cursor() as cursor: + cursor.execute(f"SELECT n, payload FROM (VALUES {values}) v(n, payload) ORDER BY n") + rows = cursor.fetchall() if method == "fetchall" else cursor.fetchmany(3) + assert [tuple(row) for row in rows] == list(enumerate(expected)) + assert cursor.messages == [] + assert cursor.fetchone() is None diff --git a/tests/test_017_fetch_buffer_sizing.py b/tests/test_017_fetch_buffer_sizing.py index c20285439..ec166c7be 100644 --- a/tests/test_017_fetch_buffer_sizing.py +++ b/tests/test_017_fetch_buffer_sizing.py @@ -23,6 +23,7 @@ "SQLDescribeCol_ptr", "SQLFreeHandle_ptr", "SQLFetch_ptr", + "SQLGetData_ptr", ) _RETAINED_CASES = ( @@ -76,6 +77,12 @@ def test_checked_fetch_buffer_preconditions(item_size, terminator): "parent-cleanup-failure", "repeat-cleanup", "lob", + "text-no-total", + "text-invalid-length", + "text-truncated", + "fast-wide", + "fast-no-total", + "fast-invalid-length", ], ) def test_fetchall_buffer_contract(conn_str, case): @@ -124,6 +131,8 @@ def _run_case(case): bindings = [] rowsets = [] fetches = [] + text_reads = [] + length_probes = [] events = [] current_size = 1 statement = None @@ -135,7 +144,9 @@ def _run_case(case): count = {"empty": 0, "small": 3, "initial-boundary": 100}.get(case, 1207) if case == "oversized-row": count = 2 - if case in ("overflow-cell", "overflow-row", "lob"): + if case in ("overflow-cell", "overflow-row", "lob") or case.startswith("text-"): + count = 3 + if case in ("fast-no-total", "fast-invalid-length"): count = 3 def install(name, args, handler): @@ -211,6 +222,29 @@ def arrow_fetch(original, handle): fetches.append(current_size) return original(handle) + def getdata(original, handle, col, ctype, data, length, indicator): + if ctype == -2 and length == 0: + length_probes.append(col) + if ctype in (1, -8) and length: + text_reads.append((ctype, data, length)) + result = original(handle, col, ctype, data, length, indicator) + if result in (0, 1) and col == 2: + output_length = ct.cast(indicator, ct.POINTER(sql_len)) + if ctype == -2 and length == 0: + if case == "text-no-total": + output_length[0] = -4 # SQL_NO_TOTAL: conservative bounded fallback. + elif case == "text-invalid-length": + output_length[0] = -99 + elif ctype in (1, -8) and case == "text-truncated": + output_length[0] = length + 2 + result = 1 + elif ctype == -8: + if case == "fast-no-total" and result == 1: + output_length[0] = -4 + elif case == "fast-invalid-length": + output_length[0] = -99 + return result + def describe(original, handle, col, name, capacity, actual, dtype, size, scale, nullable): result = original(handle, col, name, capacity, actual, dtype, size, scale, nullable) if result in (0, 1) and case == "zero-width" and col == 2: @@ -227,7 +261,8 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, ms.pooling(enabled=False) with ms.connect(os.environ["DB_CONNECTION_STRING"]) as connection: - if case in ("narrow", "overflow-row"): + fast_wide = sys.platform == "win32" and connection.getinfo(6) == "msodbcsql18.dll" + if case in ("narrow", "overflow-row") or case.startswith("text-"): connection.setdecoding(ms.SQL_CHAR, encoding="cp1252", ctype=ms.SQL_CHAR) columns = ["CAST('x' AS varchar(32))"] expected = ["x"] @@ -271,6 +306,16 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, elif case == "lob": columns += ["CAST(REPLICATE(CAST(N'y' AS nvarchar(max)), 12000) AS nvarchar(max))"] expected += ["y" * 12000] + elif case.startswith("text-"): + columns = ["CAST('x' AS varchar(8000))"] + elif case == "fast-wide": + columns = ["CAST('x' AS varchar(8000))"] * 8 + expected = ["x"] * 8 + elif case == "fast-no-total": + columns = ["CAST(REPLICATE('x', 8000) AS varchar(8000))"] + expected = ["x" * 8000] + elif case == "fast-invalid-length": + columns = ["CAST('x' AS varchar(8000))"] sql = ( "WITH d(n) AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4)," "(5),(6),(7),(8),(9)) AS v(n)) " @@ -296,6 +341,11 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, if case == "arrow-cleanup-failure": install("SQLFetch_ptr", [ct.c_void_p], arrow_fetch) install("SQLFetchScroll_ptr", [ct.c_void_p, ct.c_short, sql_len], fetch) + install( + "SQLGetData_ptr", + [ct.c_void_p, ct.c_ushort, ct.c_short, ct.c_void_p, sql_len, ct.c_void_p], + getdata, + ) install( "SQLDescribeCol_ptr", [ @@ -321,6 +371,14 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, cursor.fetchall() assert not bindings assert not fetches + elif case in ("text-invalid-length", "text-truncated", "fast-invalid-length"): + message = ( + "Invalid bounded text source length" + if case == "text-invalid-length" + else "Bounded text exceeded its probed buffer size" + ) + with pytest.raises(RuntimeError, match=message): + cursor.fetchall() elif case.endswith("-failure"): error = ( RuntimeError @@ -375,7 +433,35 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, assert tuple(sibling.fetchone()) == (42,) return - if not case.startswith("overflow-") and case != "lob" and not case.endswith("-failure"): + if case.startswith("text-"): + assert not bindings and not fetches + if case == "text-no-total": + size = 8001 if sys.platform == "win32" else 32001 + assert all(length == size for _, _, length in text_reads) + elif case in ("fast-wide", "fast-no-total", "fast-invalid-length"): + assert not bindings and not fetches + if case == "fast-wide": + assert len(text_reads) == count * 8 + assert len(length_probes) == (0 if fast_wide else count * 8) + elif case in ("wide", "narrow", "unicode", "mixed", "oversized-row"): + assert not bindings and not fetches + assert text_reads + # Full-width cells share one scratch allocation rather than a rowset. + if case in ("wide", "narrow", "unicode", "oversized-row"): + pointers_used = len({data for _, data, _ in text_reads}) + if fast_wide and case == "oversized-row": + assert pointers_used <= 16 + else: + assert len({data for _, data, _ in text_reads[-100:]}) == 1 + if case == "oversized-row": + assert max(length for _, _, length in text_reads) == (512 if fast_wide else 4) + elif case == "mixed": + assert max(length for ctype, _, length in text_reads if ctype == -8) == ( + 512 if fast_wide else 6 + ) + elif ( + not case.startswith("overflow-") and case != "lob" and not case.endswith("-failure") + ): ncols = len(columns) + 1 first = bindings[:ncols] row_bytes = sum(length + ct.sizeof(sql_len) for _, _, length in first) @@ -396,13 +482,6 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, assert fetches[:batches] == [initial] + [subsequent] * (batches - 1) assert len(fetches) == batches + 1 assert target * row_bytes <= budget or target == 1 - if case == "wide": - assert first[1][1:] == (-8, 16002) # SQL_C_WCHAR, including terminator. - elif case == "narrow": - width = 32001 if sys.platform != "win32" else 8001 - assert first[1][1:] == (1, width) - elif case == "oversized-row": - assert row_bytes > budget and initial == target == 1 elif case == "lob": assert not bindings and not fetches cursor.execute("SELECT 42") diff --git a/tests/test_query_cancellation.py b/tests/test_query_cancellation.py index f9b72455c..aff476383 100644 --- a/tests/test_query_cancellation.py +++ b/tests/test_query_cancellation.py @@ -142,13 +142,16 @@ def observe(frame, event, argument): @pytest.mark.parametrize("method", ["fetchone", "fetchmany", "fetchall"]) -def test_grouped_scalar_reads_preserve_mixed_values_and_chunk_boundaries(method): +@pytest.mark.parametrize("text_width", [10, 4000]) +def test_grouped_scalar_reads_preserve_mixed_values_and_chunk_boundaries(method, text_width): scalar_types = ("int", "smallint", "bigint", "real", "float") columns = [ f"CAST({index if index % 3 else 'NULL'} AS {scalar_types[index % 5]})" for index in range(20) ] - columns.extend(("CAST('text' AS nvarchar(10))", "CAST(-9 AS int)", "CAST(NULL AS bigint)")) + columns.extend( + (f"CAST('text' AS nvarchar({text_width}))", "CAST(-9 AS int)", "CAST(NULL AS bigint)") + ) expected = tuple(None if index % 3 == 0 else index for index in range(20)) + ( "text", -9, @@ -423,12 +426,13 @@ def test_native_cancellation_recovery_allocation_failure_retires_connection(): _run("_native_recovery_allocation_probe") -def test_grouped_scalar_cancel_prevents_later_column_calls(): +@pytest.mark.parametrize("kind", ["scalar", "text"]) +def test_grouped_scalar_cancel_prevents_later_column_calls(kind): _pointers() - _run("_grouped_scalar_boundary_probe") + _run("_grouped_scalar_boundary_probe", kind) -def _grouped_scalar_boundary_probe(): +def _grouped_scalar_boundary_probe(kind="scalar"): pointers = _pointers() callback = ctypes.WINFUNCTYPE if os.name == "nt" else ctypes.CFUNCTYPE getdata_type = callback( @@ -442,8 +446,9 @@ def _grouped_scalar_boundary_probe(): ) cancel_type = callback(ctypes.c_short, ctypes.c_void_p) with _connection() as connection, connection.cursor() as cursor: - cursor.execute("SELECT 1, 2, 3, 4 FROM (VALUES (1), (2)) AS source(n)") - assert tuple(cursor.fetchone()) == (1, 2, 3, 4) + value = "CAST(N'text' AS nvarchar(4000))" if kind == "text" else "2" + cursor.execute(f"SELECT 1, {value}, 3, 4 FROM (VALUES (1), (2)) AS source(n)") + assert tuple(cursor.fetchone()) == (1, "text" if kind == "text" else 2, 3, 4) original_getdata = pointers["SQLGetData_ptr"].value original_cancel = pointers["SQLCancel_ptr"].value getdata = getdata_type(original_getdata) @@ -471,7 +476,10 @@ def cancel(_): pointers["SQLCancel_ptr"].value = ctypes.cast(cancel, ctypes.c_void_p).value try: with pytest.raises(OperationalError, match="Operation canceled"): - cursor.fetchone() + if kind == "text": + cursor.fetchall() + else: + cursor.fetchone() finally: pointers["SQLGetData_ptr"].value = original_getdata pointers["SQLCancel_ptr"].value = original_cancel @@ -479,7 +487,10 @@ def cancel(_): profiling.disable() assert reads == [1, 2] if profiling is not None: - assert profiling.get_stats()["ddbc::SQLGetData::scalar_group"]["calls"] == 1 + if kind == "scalar": + assert profiling.get_stats()["ddbc::SQLGetData::scalar_group"]["calls"] == 1 + elif os.name == "nt" and connection.getinfo(6) == "msodbcsql18.dll": + assert profiling.get_stats()["ddbc::SQLGetData::short_cell_group"]["calls"] == 1 assert cursor._query_slot.active is None assert not connection._query_state.busy assert cursor.execute("SELECT 99").fetchone()[0] == 99 From 2068695b0f268485836fe8e3cd672810719b1060 Mon Sep 17 00:00:00 2001 From: Jahnvi Thakkar Date: Fri, 27 Nov 2026 11:43:57 +0530 Subject: [PATCH 06/14] PERF: replace per-cell text reads with reusable bounded rowsets Decode directly from smaller complete rowsets, adapt dense results to the standard budget, and retain safe binding lifetimes. Validate row counts and lengths without adding checks to unchanged fetch paths. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 19 +- mssql_python/pybind/ddbc_bindings.cpp | 448 ++++++-------------------- tests/test_017_fetch_bounded_text.py | 81 +++++ tests/test_017_fetch_buffer_sizing.py | 166 ++++++---- tests/test_query_cancellation.py | 28 +- 5 files changed, 311 insertions(+), 431 deletions(-) diff --git a/README.md b/README.md index 427520517..9d80be00b 100644 --- a/README.md +++ b/README.md @@ -490,17 +490,20 @@ strings do not require a character-by-character scan. Wide-character retrieval of `VARCHAR(MAX)` values uses a non-consuming binary length probe to size the conversion buffer, avoiding character loss at truncated UTF-16 conversion boundaries while preserving embedded and trailing NULs. -The experimental bounded-text path uses ordered, unbound reads for `fetchall()` +The experimental bounded-text path uses complete, reusable rowsets for `fetchall()` and `fetchmany()` when a text column is wider than 256 declared characters, reusing storage rather than allocating every cell at its declared width. -On Windows with `msodbcsql18`, short values need one read into a 512-byte starter -buffer; longer values preserve that prefix and grow reusable storage. -Up to 16 adjacent text/scalar reads share a GIL release, while retaining -per-column cancellation and diagnostic handling. Other providers/platforms and -narrow decoding retain conservative length probing. +Bound storage targets 1 MiB including indicators, with at least one complete row +and at most 1,000 rows (at most 100 initially). Values are decoded directly into +actual-length Python results, without a second native copy or per-cell length probes. +When observed payload occupies at least half the declared row width, storage +can grow once to the ordinary 8 MiB rowset budget. Every driver fetch retains +cancellation and diagnostic handling; rebinding preserves cleanup lifetimes. Fixed-width and short-text result sets retain rowset batching. Wide-text result -sets still trade additional driver calls for lower temporary buffer use and can -be slower for large results; they do not change the forward-only cursor type. +sets trade smaller rowsets and additional driver calls for lower temporary +buffer use. They do not change the forward-only cursor type or recover truncated +multirow bindings with `SQLGetData`. A row larger than either budget remains +complete; Python results and allocator overhead are outside those targets. Result sets containing LOB columns retain their existing streaming path. The 256-character cutoff is provisional, not a tuned throughput threshold. Explicit `setinputsizes()` SQL types and sizes still take precedence. An explicit diff --git a/mssql_python/pybind/ddbc_bindings.cpp b/mssql_python/pybind/ddbc_bindings.cpp index 2dc7249a4..c14e38e21 100644 --- a/mssql_python/pybind/ddbc_bindings.cpp +++ b/mssql_python/pybind/ddbc_bindings.cpp @@ -3938,161 +3938,6 @@ static bool IsBoundedFetchText(SQLSMALLINT type, SQLULEN size) { type == SQL_WCHAR || type == SQL_WVARCHAR || type == SQL_WLONGVARCHAR); } -struct FetchTextScratch { - static constexpr size_t shortUnits = 256; - std::vector wide; - std::vector narrow; -#if defined(_WIN32) - const bool fastWideReads = GetSelectedProviderId() == kProviderMsodbcsql18; -#else - // Unix VARCHAR-to-WCHAR truncation can consume characters that did not fit. - const bool fastWideReads = false; -#endif - - SQLLEN readWideParts(const SqlHandlePtr& handle, SQLUSMALLINT column, py::handle messages, - const SQLWCHAR* first = nullptr, SQLLEN firstLength = 0) { - PERF_TIMER("FetchTextScratch::readWideParts"); - wide.resize(std::max(wide.size(), shortUnits)); - if (first) - std::copy_n(first, shortUnits, wide.data()); - bool pending = first != nullptr; - size_t used = 0; - while (true) { - const size_t available = (wide.size() - used) * sizeof(SQLWCHAR); - const size_t payload = available - sizeof(SQLWCHAR); - SQLLEN length = firstLength; - SQLRETURN ret = SQL_SUCCESS_WITH_INFO; - if (!pending) - ret = CancellableGetData(handle->get(), column, SQL_C_WCHAR, wide.data() + used, - available, &length); - pending = false; - const bool truncated = - ret == SQL_SUCCESS_WITH_INFO && - (length == SQL_NO_TOTAL || (length >= 0 && static_cast(length) > payload)); - CaptureFetchDiagnostics(handle->get(), ret, messages, truncated); - CheckFetchError(handle, ret); - if (length == SQL_NULL_DATA && SQL_SUCCEEDED(ret) && used == 0) - return SQL_NULL_DATA; - if (!SQL_SUCCEEDED(ret) || (length < 0 && !(truncated && length == SQL_NO_TOTAL)) || - (length >= 0 && length % sizeof(SQLWCHAR)) || - (!truncated && static_cast(length) > payload)) - ThrowStdException("Bounded text exceeded its probed buffer size"); - if (!truncated) - return static_cast(used * sizeof(SQLWCHAR) + length); - - const size_t prefix = used * sizeof(SQLWCHAR); - size_t bytes; - if (length == SQL_NO_TOTAL) { - bytes = CheckedFetchBufferBytes(wide.size(), sizeof(SQLWCHAR) * 2, 0); - } else { - const size_t limit = static_cast(std::numeric_limits::max()); - if (prefix > limit - sizeof(SQLWCHAR) || - static_cast(length) > limit - prefix - sizeof(SQLWCHAR)) - throw std::length_error("Fetch buffer size exceeds supported limits"); - bytes = prefix + static_cast(length) + sizeof(SQLWCHAR); - } - used += payload / sizeof(SQLWCHAR); - wide.resize(bytes / sizeof(SQLWCHAR)); - } - } - - py::object read(const SqlHandlePtr& handle, SQLUSMALLINT column, SQLSMALLINT type, - SQLULEN declaredSize, int charCtype, const std::string& encoding, - py::handle messages, py::handle converters) { - const bool unicode = type == SQL_WCHAR || type == SQL_WVARCHAR || type == SQL_WLONGVARCHAR; - const bool useWide = unicode || charCtype == SQL_C_WCHAR; - SQLLEN length = 0; - if (useWide && fastWideReads) { - length = readWideParts(handle, column, messages); - if (length == SQL_NULL_DATA) - return py::none(); - } else { - SQLLEN sourceLength = 0; - // A zero-byte binary probe does not consume nonempty text or perform a potentially - // lossy truncated VARCHAR-to-WCHAR conversion on Unix. - SQLRETURN ret = - CancellableGetData(handle->get(), column, SQL_C_BINARY, nullptr, 0, &sourceLength); - CaptureFetchDiagnostics(handle->get(), ret, messages, true); - CheckFetchError(handle, ret); - if (!SQL_SUCCEEDED(ret)) - ThrowStdException("Failed to probe bounded text length"); - if (sourceLength == SQL_NULL_DATA) - return py::none(); - if (sourceLength == SQL_NO_TOTAL) { - sourceLength = static_cast( - CheckedFetchBufferBytes(declaredSize, unicode ? sizeof(SQLWCHAR) : 1, 0)); - } else if (sourceLength < 0) { - ThrowStdException("Invalid bounded text source length"); - } - if (sourceLength == 0) { - // A successful zero-length probe already exhausts an empty value. - return decode(column, unicode, useWide, "", 0, encoding, converters); - } - size_t expansion = useWide && !unicode ? sizeof(SQLWCHAR) : 1; -#if defined(__APPLE__) || defined(__linux__) - if (!useWide) - expansion = 4; -#endif - const size_t terminator = useWide ? sizeof(SQLWCHAR) : 1; - const size_t bytes = CheckedFetchBufferBytes(sourceLength, expansion, terminator); - SQLPOINTER data; - if (useWide) { - if (bytes % sizeof(SQLWCHAR)) - ThrowStdException("Unaligned bounded UTF-16 text length"); - wide.resize(bytes / sizeof(SQLWCHAR)); - data = wide.data(); - } else { - narrow.resize(bytes); - data = narrow.data(); - } - ret = CancellableGetData(handle->get(), column, useWide ? SQL_C_WCHAR : SQL_C_CHAR, - data, static_cast(bytes), &length); - CaptureFetchDiagnostics(handle->get(), ret, messages); - CheckFetchError(handle, ret); - if (!SQL_SUCCEEDED(ret) || length < 0 || - static_cast(length) > bytes - terminator || - (useWide && length % sizeof(SQLWCHAR))) - ThrowStdException("Bounded text exceeded its probed buffer size"); - } - const auto* text = useWide ? reinterpret_cast(wide.data()) - : reinterpret_cast(narrow.data()); - return decode(column, unicode, useWide, text, length, encoding, converters); - } - - static py::object decode(SQLUSMALLINT column, bool unicode, bool useWide, - const char* text, SQLLEN length, const std::string& encoding, - py::handle converters) { - if (useWide && OutputConverters::enabled(converters, column - 1)) { - py::object converted = OutputConverters::text(text, length); - if (converted) - return converted; - } - if (!length) - return py::str(""); - PyObject* decoded; - if (unicode) - decoded = FetchText::decode_batch_utf16_native(text, length); - else if (useWide) { -#if defined(_WIN32) - decoded = PyUnicode_FromWideChar(reinterpret_cast(text), - length / sizeof(SQLWCHAR)); -#else - decoded = FetchText::decode_utf16_native(text, length); -#endif - } else { - const auto codec = GetEffectiveCharDecoding(encoding); - decoded = PyUnicode_Decode(text, length, codec.c_str(), "strict"); - } - if (!decoded) { - PyErr_Clear(); - decoded = PyBytes_FromStringAndSize(text, length); - } - if (!decoded) - throw py::error_already_set(); - return steal(decoded); - } -}; - static SQLSMALLINT FixedScalarCType(SQLSMALLINT type) { switch (type) { case SQL_INTEGER: return SQL_C_LONG; @@ -4173,136 +4018,12 @@ static size_t FetchFixedScalarRun(SQLHSTMT statement, StatementOperation* operat return read; } -static size_t FetchShortCellRun( - const SqlHandlePtr& handle, StatementOperation* operation, const ResultMetadata& metadata, - size_t first, size_t count, py::list& row, FetchTextScratch& scratch, int charCtype, - const std::string& encoding, py::handle messages, py::handle converters, SQLRETURN& result) { - if (!scratch.fastWideReads || scratch.wide.size() > FetchTextScratch::shortUnits) - return 0; - constexpr size_t capacity = 16; - std::array types; - size_t length = 0; - while (length < capacity && first + length < count) { - const auto& column = metadata.columns[first + length]; - const bool unicode = column.dataType == SQL_WCHAR || column.dataType == SQL_WVARCHAR || - column.dataType == SQL_WLONGVARCHAR; - const auto scalar = FixedScalarCType(column.dataType); - const bool text = IsBoundedFetchText(column.dataType, column.columnSize) && - (unicode || charCtype == SQL_C_WCHAR); - if (!text && !scalar) - break; - types[length] = text ? SQL_C_WCHAR : scalar; - ++length; - } - if (length < 2) - return 0; - - struct Cell { - std::array data; - SQLINTEGER integer; - SQLSMALLINT smallInteger; - SQLBIGINT big; - SQLREAL real; - SQLDOUBLE floating; - SQLLEN indicator = 0; - SQLPOINTER buffer(SQLSMALLINT type) { - switch (type) { - case SQL_C_LONG: return &integer; - case SQL_C_SHORT: return &smallInteger; - case SQL_C_SBIGINT: return &big; - case SQL_C_FLOAT: return ℜ - case SQL_C_DOUBLE: return &floating; - default: return data.data(); - } - } - }; - std::array cells; - constexpr size_t payload = (FetchTextScratch::shortUnits - 1) * sizeof(SQLWCHAR); - SQLHSTMT statement = handle->get(); - size_t read = 0; - bool admitted = true; - PERF_TIMER("SQLGetData::short_cell_group"); - { - py::gil_scoped_release release; - for (; read < length;) { - auto& cell = cells[read]; - const auto type = types[read]; - result = CancellableCallWithoutGIL( - operation, - [&] { - return SQLGetData_ptr(statement, static_cast(first + read + 1), - type, cell.buffer(type), sizeof(cell.data), - &cell.indicator); - }, - admitted); - ++read; - // Stop before another call overwrites diagnostics or consumes later - // columns after an invalid length. Each read retains its cancellation fence. - if (result != SQL_SUCCESS || - (cell.indicator != SQL_NULL_DATA && - (cell.indicator < 0 || static_cast(cell.indicator) > payload || - cell.indicator % sizeof(SQLWCHAR)))) - break; - } - } - result = operation->checkResult(statement, result, admitted); - const auto& last = cells[read - 1]; - const bool truncated = types[read - 1] == SQL_C_WCHAR && result == SQL_SUCCESS_WITH_INFO && - (last.indicator == SQL_NO_TOTAL || - (last.indicator >= 0 && static_cast(last.indicator) > payload)); - if (!truncated) - CaptureFetchDiagnostics(statement, result, messages); - if (result == SQL_NO_DATA) - ThrowStdException("Bounded text exceeded its probed buffer size"); - if (!SQL_SUCCEEDED(result)) - return read; - - for (size_t index = 0; index < read; ++index) { - const auto& cell = cells[index]; - if (cell.indicator == SQL_NULL_DATA) { - row.append(py::none()); - continue; - } - const auto column = static_cast(first + index + 1); - if (types[index] != SQL_C_WCHAR) { - if (cell.indicator < 0 || static_cast(cell.indicator) > payload) - ThrowStdException("Invalid bounded scalar length"); - switch (types[index]) { - case SQL_C_LONG: row.append(static_cast(cell.integer)); break; - case SQL_C_SHORT: row.append(static_cast(cell.smallInteger)); break; - case SQL_C_SBIGINT: row.append(static_cast(cell.big)); break; - case SQL_C_FLOAT: row.append(cell.real); break; - default: row.append(cell.floating); break; - } - continue; - } - const bool unicode = metadata.columns[first + index].dataType == SQL_WCHAR || - metadata.columns[first + index].dataType == SQL_WVARCHAR || - metadata.columns[first + index].dataType == SQL_WLONGVARCHAR; - if (truncated && index + 1 == read) { - const auto bytes = - scratch.readWideParts(handle, column, messages, cell.data.data(), cell.indicator); - row.append(FetchTextScratch::decode(column, unicode, true, - reinterpret_cast(scratch.wide.data()), - bytes, encoding, converters)); - } else { - if (cell.indicator < 0 || static_cast(cell.indicator) > payload || - cell.indicator % sizeof(SQLWCHAR)) - ThrowStdException("Bounded text exceeded its probed buffer size"); - row.append(FetchTextScratch::decode(column, unicode, true, - reinterpret_cast(cell.data.data()), - cell.indicator, encoding, converters)); - } - } - return read; -} - static SQLRETURN GetRowData(const SqlHandlePtr& StatementHandle, SQLUSMALLINT colCount, py::list& row, const std::string& charEncoding, const std::string& wcharEncoding, int charCtype, py::handle messages, const ResultMetadataCache::Snapshot& snapshot, bool completeResult = false, py::handle converters = {}, - bool batchText = false, FetchTextScratch* textScratch = nullptr) { + bool batchText = false) { PERF_TIMER("SQLGetData_wrap"); // Note: wcharEncoding parameter is reserved for future use // Currently WCHAR data always uses UTF-16LE for Windows compatibility @@ -4335,17 +4056,6 @@ static SQLRETURN GetRowData(const SqlHandlePtr& StatementHandle, SQLUSMALLINT co (!converters || converters.is_none() || (PyDict_CheckExact(converters.ptr()) && PyDict_Size(converters.ptr()) == 0)); for (SQLSMALLINT i = 1; i <= colCount; ++i) { - if (textScratch && operation && metadata) { - const auto read = FetchShortCellRun( - StatementHandle, operation, *metadata, static_cast(i - 1), colCount, - row, *textScratch, charCtype, charEncoding, messages, converters, ret); - if (read) { - if (!SQL_SUCCEEDED(ret)) - return ret; - i += static_cast(read - 1); - continue; - } - } if (groupScalars) { const auto read = FetchFixedScalarRun(hStmt, operation, *metadata, static_cast(i - 1), colCount, @@ -4459,11 +4169,6 @@ static SQLRETURN GetRowData(const SqlHandlePtr& StatementHandle, SQLUSMALLINT co (long)variantCType, effectiveDataType); } - if (textScratch && IsBoundedFetchText(dataType, columnSize)) { - row.append(textScratch->read(StatementHandle, i, dataType, columnSize, charCtype, - charEncoding, messages, converters)); - continue; - } switch (effectiveDataType) { case SQL_CHAR: case SQL_VARCHAR: @@ -5479,31 +5184,39 @@ SQLRETURN SQLBindColums(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& return ret; } +static void ValidateBoundCellLength(SQLSMALLINT type, SQLLEN indicator, size_t capacity, + bool wide) { + const bool text = IsBoundedFetchText(type, 1); + const bool decimal = type == SQL_DECIMAL || type == SQL_NUMERIC; + const size_t terminator = text ? (wide ? sizeof(SQLWCHAR) : 1) : (decimal ? 1 : 0); + if (indicator != SQL_NULL_DATA && + (indicator < 0 || static_cast(indicator) > capacity - terminator || + (wide && indicator % sizeof(SQLWCHAR)))) + ThrowStdException("Invalid bounded fetch length"); +} + // Fetch rows in batches // TODO: Move to anonymous namespace, since it is not used outside this file -template +template SQLRETURN FetchBatchData(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& columnNames, py::list& rows, SQLUSMALLINT numCols, SQLULEN& numRowsFetched, const std::vector& lobColumns, const std::string& charEncoding = "utf-16le", int charCtype = SQL_C_WCHAR, - py::handle messages = {}, py::handle converters = {}) { + py::handle messages = {}, py::handle converters = {}, + size_t maximumRows = 0) { PERF_TIMER("FetchBatchData"); - LOG("FetchBatchData: Fetching data in batches"); + numRowsFetched = 0; SQLRETURN ret; { PERF_TIMER("FetchBatchData::SQLFetchScroll_call"); ret = CancellableCall(hStmt, [&] { return SQLFetchScroll_ptr(hStmt, SQL_FETCH_NEXT, 0); }); } CaptureFetchDiagnostics(hStmt, ret, messages); - if (ret == SQL_NO_DATA) { - LOG("FetchBatchData: No data to fetch"); - return ret; - } - if (!SQL_SUCCEEDED(ret)) { - LOG("FetchBatchData: Error while fetching rows in batches - " - "SQLRETURN=%d", - ret); + if (!SQL_SUCCEEDED(ret)) return ret; + if constexpr (strictLengths) { + if (numRowsFetched == 0 || numRowsFetched > maximumRows) + ThrowStdException("Invalid bounded fetch row count"); } // Pre-cache column metadata to avoid repeated dictionary lookups. // The vectors below are consumed later by construct_rows, so they are @@ -5516,6 +5229,7 @@ SQLRETURN FetchBatchData(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& SQLULEN columnSize; SQLULEN processedColumnSize; uint64_t fetchBufferSize; + size_t bufferBytes; bool isLob; }; const bool useWideChar = (charCtype == SQL_C_WCHAR); @@ -5540,6 +5254,9 @@ SQLRETURN FetchBatchData(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& HandleZeroColumnSizeAtFetch(columnInfos[col].processedColumnSize); SQLSMALLINT dt = columnInfos[col].dataType; + columnInfos[col].bufferBytes = + strictLengths ? BoundColumnBufferBytes(dt, columnInfos[col].columnSize, charCtype) + : 0; if (dt == SQL_CHAR || dt == SQL_VARCHAR || dt == SQL_LONGVARCHAR || dt == SQL_WCHAR || dt == SQL_WVARCHAR || dt == SQL_WLONGVARCHAR) { const bool wide = useWideChar || @@ -5655,6 +5372,10 @@ SQLRETURN FetchBatchData(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& // functions This eliminates redundant NULL checks inside each // processor and improves CPU branch prediction SQLLEN dataLen = buffers.indicators[col - 1][i]; + if constexpr (strictLengths) + ValidateBoundCellLength(columnInfos[col - 1].dataType, dataLen, + columnInfos[col - 1].bufferBytes, + !buffers.wcharBuffers[col - 1].empty()); // Handle NULL and special indicator values first (applies to ALL // types) @@ -5830,8 +5551,9 @@ SQLRETURN FetchBatchData(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& return ret; } -static size_t BoundRowBufferBytes(const py::list& columnNames, SQLUSMALLINT numCols, - int charCtype) { +template +static size_t BoundRowBufferBytes(const Metadata& columnNames, SQLUSMALLINT numCols, + int charCtype) { size_t rowSize = 0; const size_t limit = static_cast(std::numeric_limits::max()); for (SQLUSMALLINT col = 0; col < numCols; ++col) { @@ -5931,41 +5653,76 @@ struct FetchStateGuard { } }; -// SQL_GD_BLOCK does not permit SQLGetData on multirow forward-only cursors. -// Keep every column unbound and read in order; no driver pointers outlive a call. -static SQLRETURN FetchDynamicTextRows( - const SqlHandlePtr& handle, SQLUSMALLINT numCols, py::list& rows, size_t limit, - const std::string& charEncoding, const std::string& wcharEncoding, int charCtype, - py::handle messages, py::handle converters) { - PERF_TIMER("FetchDynamicTextRows"); - if (!handle->fetchColumnsUnbound) { - SQLRETURN ret = SQLFreeStmt_ptr(handle->get(), SQL_UNBIND); - CaptureFetchDiagnostics(handle->get(), ret, messages); - CheckFetchError(handle, ret); - if (!SQL_SUCCEEDED(ret)) - return ret; - handle->fetchColumnsUnbound = true; - } - FetchTextScratch scratch; - for (size_t count = 0; count < limit; ++count) { - SQLRETURN ret = CancellableCall(handle->get(), [&] { - return SQLFetch_ptr(handle->get()); - }); - CaptureFetchDiagnostics(handle->get(), ret, messages); +// Decode complete cells directly from a small reusable rowset. Python results +// own actual-length values; no truncated binding or SQLGetData recovery is needed. +static SQLRETURN FetchReusableTextRows(const SqlHandlePtr& handle, SQLUSMALLINT numCols, + py::list& rows, size_t limit, + const std::string& charEncoding, + const std::string& wcharEncoding, int charCtype, + py::handle messages, py::handle converters) { + PERF_TIMER("FetchReusableTextRows"); + (void)wcharEncoding; + if (limit == 0) + return SQL_SUCCESS; + const auto metadata = handle->resultMetadata.snapshot().metadata; + if (!metadata || metadata->columns.size() != numCols) + ThrowStdException("Column metadata count does not match result column count"); + const auto& columns = metadata->columns; + constexpr size_t maximumRows = 1000; + constexpr size_t denseBudget = size_t{8} * 1024 * 1024; + constexpr size_t bindingBudget = size_t{1} * 1024 * 1024; + const size_t boundBytes = BoundRowBufferBytes(columns, numCols, charCtype); + const size_t sparseRows = + std::min(limit, std::clamp(bindingBudget / boundBytes, 1, maximumRows)); + size_t boundRows = std::min(sparseRows, size_t{100}); + FetchStateGuard guard(handle, messages, numCols, static_cast(boundRows)); + SQLHSTMT statement = handle->get(); + SQLRETURN ret = SQLBindColums(statement, guard.storage->columns, columns, numCols, + static_cast(boundRows), charCtype, messages); + guard.observe(ret); + guard.configure(boundRows); + size_t configuredRows = boundRows; + bool dense = false; + for (size_t count = 0; count < limit;) { + const size_t rowArray = std::min(boundRows, limit - count); + if (rowArray != configuredRows) { + guard.setRowArraySize(rowArray); + configuredRows = rowArray; + } + ret = FetchBatchData(statement, guard.storage->columns, columns, rows, numCols, + guard.storage->rowsFetched, {}, charEncoding, charCtype, messages, + converters, rowArray); CheckFetchError(handle, ret); if (ret == SQL_NO_DATA) break; if (!SQL_SUCCEEDED(ret)) return ret; - py::list row; - ret = GetRowData(handle, numCols, row, charEncoding, wcharEncoding, charCtype, - messages, handle->resultMetadata.snapshot(), true, converters, - true, &scratch); - CheckFetchError(handle, ret); - if (!SQL_SUCCEEDED(ret)) - return ret; - rows.append(row); + const size_t fetched = guard.storage->rowsFetched; + size_t bytes = 0; + if (!dense) + for (size_t column = 0; column < numCols; ++column) + for (size_t row = 0; row < fetched; ++row) + if (guard.storage->columns.indicators[column][row] >= 0) + bytes += + static_cast(guard.storage->columns.indicators[column][row]); + count += fetched; + if (!dense && count < limit) { + dense = bytes / fetched >= boundBytes / 2; + // Dense values benefit from the regular larger rowset budget. + const size_t targetRows = + dense ? std::clamp(denseBudget / boundBytes, 1, maximumRows) : sparseRows; + const size_t batchRows = std::min(limit - count, targetRows); + if (batchRows <= boundRows) + continue; + guard.observe(SQLFreeStmt_ptr(statement, SQL_UNBIND)); + guard.storage->columns = ColumnBuffers(numCols, static_cast(batchRows)); + ret = SQLBindColums(statement, guard.storage->columns, columns, numCols, + static_cast(batchRows), charCtype, messages); + guard.observe(ret); + boundRows = batchRows; + } } + guard.close(); return SQL_SUCCESS; } @@ -6054,8 +5811,8 @@ SQLRETURN FetchMany_wrap(SqlHandlePtr StatementHandle, py::list& rows, int fetch } if (dynamicText && lobColumns.empty()) - return FetchDynamicTextRows(StatementHandle, numCols, rows, fetchSize, - charEncoding, wcharEncoding, charCtype, messages, converters); + return FetchReusableTextRows(StatementHandle, numCols, rows, fetchSize, charEncoding, + wcharEncoding, charCtype, messages, converters); if (singleRowEligible) { py::list row; @@ -7312,9 +7069,8 @@ SQLRETURN FetchAll_wrap(SqlHandlePtr StatementHandle, py::list& rows, // If we have LOBs → fall back to row-by-row fetch + SQLGetData_wrap if (!lobColumns.empty() || dynamicText) { - LOG("FetchAll_wrap: LOB columns detected (%zu columns), using per-row " - "SQLGetData path", - lobColumns.size()); + LOG("FetchAll_wrap: LOB columns=%zu, reusable bounded text=%d", lobColumns.size(), + dynamicText); if (numCols < 0 || columnNames.size() != static_cast(numCols)) { LOG("FetchAll_wrap: Column metadata count does not match result column count"); ThrowStdException("Column metadata count does not match result column count"); @@ -7334,9 +7090,9 @@ SQLRETURN FetchAll_wrap(SqlHandlePtr StatementHandle, py::list& rows, } StatementHandle->resultMetadata.publish(metadataSnapshot.generation, std::move(metadata)); if (lobColumns.empty()) - return FetchDynamicTextRows( - StatementHandle, numCols, rows, std::numeric_limits::max(), - charEncoding, wcharEncoding, charCtype, messages, converters); + return FetchReusableTextRows(StatementHandle, numCols, rows, + std::numeric_limits::max(), charEncoding, + wcharEncoding, charCtype, messages, converters); while (true) { ret = CancellableCall(hStmt, [&] { return SQLFetch_ptr(hStmt); }); CaptureFetchDiagnostics(hStmt, ret, messages); diff --git a/tests/test_017_fetch_bounded_text.py b/tests/test_017_fetch_bounded_text.py index e76d17c10..83de9f07f 100644 --- a/tests/test_017_fetch_bounded_text.py +++ b/tests/test_017_fetch_bounded_text.py @@ -14,6 +14,42 @@ from mssql_python import SQL_CHAR, SQL_WCHAR +@pytest.mark.parametrize("dense_first", [False, True]) +@pytest.mark.parametrize("batch_size", [None, 7, 9, 65], ids=["all", "many7", "many9", "many65"]) +def test_reusable_rowsets_preserve_density_transitions(db_connection, dense_first, batch_size): + full = "x" * 3998 + "\U0001f642" + expression = ( + f"CAST(CASE WHEN {'n < 16' if dense_first else 'n >= 16'} THEN ? " + "WHEN n % 4 = 0 THEN NULL WHEN n % 4 = 1 THEN N'' " + "WHEN n % 4 = 2 THEN N'A' + NCHAR(0) + N'B' " + "ELSE CAST(0x3DD842DE AS nvarchar(2)) END AS nvarchar(4000))" + ) + sql = ( + "WITH d(n) AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4)," + "(5),(6),(7),(8),(9)) AS v(n)), " + "numbers AS (SELECT a.n + 10*b.n + 100*c.n AS n " + "FROM d a CROSS JOIN d b CROSS JOIN d c) " + f"SELECT n, {', '.join([expression] * 8)} FROM numbers WHERE n < 137 ORDER BY n" + ) + with db_connection.cursor() as cursor: + cursor.execute(sql, (full,) * 8) + if batch_size is None: + rows = cursor.fetchall() + else: + rows = [] + while batch := cursor.fetchmany(batch_size): + assert len(batch) <= batch_size + rows.extend(batch) + expected = [] + for n in range(137): + dense = n < 16 if dense_first else n >= 16 + value = full if dense else (None, "", "A\0B", "\U0001f642")[n % 4] + expected.append((n,) + (value,) * 8) + assert [tuple(row) for row in rows] == expected + assert cursor.fetchmany(9) == [] + assert cursor.fetchone() is None + + @pytest.fixture(scope="module") def utf8_collation(db_connection): with db_connection.cursor() as cursor: @@ -27,6 +63,51 @@ def utf8_collation(db_connection): return row[0] +def test_reusable_rowset_mixed_native_types_and_nulls(db_connection): + from datetime import date, datetime, time + from decimal import Decimal + from uuid import UUID + + columns = [ + ("N'wide'", "nvarchar(4000)", "wide"), + ("1", "int", 1), + ("2", "smallint", 2), + ("3", "bigint", 3), + ("4", "tinyint", 4), + ("1", "bit", True), + ("1.5", "real", 1.5), + ("2.5", "float", 2.5), + ("12.50", "decimal(10,2)", Decimal("12.50")), + ("0x0001", "varbinary(2)", b"\0\x01"), + ("'2026-01-02'", "date", date(2026, 1, 2)), + ("'03:04:05.123456'", "time(6)", time(3, 4, 5, 123456)), + ( + "'2026-01-02T03:04:05.123456'", + "datetime2(6)", + datetime(2026, 1, 2, 3, 4, 5, 123456), + ), + ( + "'2026-01-02T03:04:05.123456+05:30'", + "datetimeoffset(6)", + datetime.fromisoformat("2026-01-02T03:04:05.123456+05:30"), + ), + ( + "'00112233-4455-6677-8899-aabbccddeeff'", + "uniqueidentifier", + UUID("00112233-4455-6677-8899-aabbccddeeff"), + ), + ] + expressions = [ + f"CAST(CASE WHEN n = 0 THEN {literal} END AS {sqltype})" for literal, sqltype, _ in columns + ] + with db_connection.cursor() as cursor: + cursor.execute(f"SELECT {', '.join(expressions)} FROM (VALUES (0),(1)) AS v(n) ORDER BY n") + assert [tuple(row) for row in cursor.fetchall()] == [ + tuple(value for _, _, value in columns), + (None,) * len(columns), + ] + + def _fetch_rows(cursor, method): if method == "fetchall": rows = cursor.fetchall() diff --git a/tests/test_017_fetch_buffer_sizing.py b/tests/test_017_fetch_buffer_sizing.py index ec166c7be..9dc7c21b8 100644 --- a/tests/test_017_fetch_buffer_sizing.py +++ b/tests/test_017_fetch_buffer_sizing.py @@ -77,12 +77,17 @@ def test_checked_fetch_buffer_preconditions(item_size, terminator): "parent-cleanup-failure", "repeat-cleanup", "lob", - "text-no-total", - "text-invalid-length", - "text-truncated", - "fast-wide", - "fast-no-total", - "fast-invalid-length", + "compact-wide", + "compact-medium", + "compact-no-total", + "compact-invalid-length", + "compact-truncated", + "compact-invalid-scalar", + "compact-fetch-error", + "compact-odd-wide-length", + "compact-zero-rows", + "compact-excess-rows", + "compact-dense-truncated", ], ) def test_fetchall_buffer_contract(conn_str, case): @@ -131,11 +136,13 @@ def _run_case(case): bindings = [] rowsets = [] fetches = [] + bound_cells = {} text_reads = [] length_probes = [] events = [] current_size = 1 statement = None + fetched_pointer = None lifetime = None persistent = case in _RETAINED_CASES sql_len = ct.c_ssize_t @@ -144,10 +151,10 @@ def _run_case(case): count = {"empty": 0, "small": 3, "initial-boundary": 100}.get(case, 1207) if case == "oversized-row": count = 2 - if case in ("overflow-cell", "overflow-row", "lob") or case.startswith("text-"): - count = 3 - if case in ("fast-no-total", "fast-invalid-length"): + if case in ("overflow-cell", "overflow-row", "lob") or case.startswith("compact-"): count = 3 + if case in ("compact-wide", "compact-medium", "compact-dense-truncated"): + count = 1207 def install(name, args, handler): pointer = pointers[name] @@ -162,6 +169,7 @@ def bind(original, handle, col, ctype, data, length, indicator): nonlocal statement statement = handle bindings.append((col, ctype, length)) + bound_cells[col] = (length, indicator, data) events.append("bind") if case == "bind-failure" and fetches: return -2 @@ -174,7 +182,9 @@ def bind(original, handle, col, ctype, data, length, indicator): return original(handle, col, ctype, data, length, indicator) def attr(original, handle, attribute, value, length): - nonlocal current_size + nonlocal current_size, fetched_pointer + if attribute == 26 and value: + fetched_pointer = value if ( case in ("persistent-rows-fetched-failure", "arrow-cleanup-failure") and attribute == 26 @@ -216,7 +226,27 @@ def free_handle(original, kind, handle): def fetch(original, handle, orientation, offset): fetches.append(current_size) events.append("fetch") - return original(handle, orientation, offset) + result = original(handle, orientation, offset) + if result in (0, 1): + if case in ("compact-zero-rows", "compact-excess-rows"): + output_count = ct.cast(fetched_pointer, ct.POINTER(sql_ulen)) + output_count[0] = 0 if case == "compact-zero-rows" else current_size + 1 + if case == "compact-fetch-error": + return -2 + column = 1 if case == "compact-invalid-scalar" else 2 + capacity, indicator, _ = bound_cells[column] + output_length = ct.cast(indicator, ct.POINTER(sql_len)) + if case == "compact-no-total": + output_length[0] = -4 + elif case in ("compact-invalid-length", "compact-invalid-scalar"): + output_length[0] = -99 + elif case == "compact-truncated": + output_length[0] = capacity + 2 + elif case == "compact-odd-wide-length": + output_length[0] = 1 + elif case == "compact-dense-truncated" and len(fetches) > 1: + output_length[0] = capacity + 2 + return result def arrow_fetch(original, handle): fetches.append(current_size) @@ -227,23 +257,7 @@ def getdata(original, handle, col, ctype, data, length, indicator): length_probes.append(col) if ctype in (1, -8) and length: text_reads.append((ctype, data, length)) - result = original(handle, col, ctype, data, length, indicator) - if result in (0, 1) and col == 2: - output_length = ct.cast(indicator, ct.POINTER(sql_len)) - if ctype == -2 and length == 0: - if case == "text-no-total": - output_length[0] = -4 # SQL_NO_TOTAL: conservative bounded fallback. - elif case == "text-invalid-length": - output_length[0] = -99 - elif ctype in (1, -8) and case == "text-truncated": - output_length[0] = length + 2 - result = 1 - elif ctype == -8: - if case == "fast-no-total" and result == 1: - output_length[0] = -4 - elif case == "fast-invalid-length": - output_length[0] = -99 - return result + return original(handle, col, ctype, data, length, indicator) def describe(original, handle, col, name, capacity, actual, dtype, size, scale, nullable): result = original(handle, col, name, capacity, actual, dtype, size, scale, nullable) @@ -261,12 +275,11 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, ms.pooling(enabled=False) with ms.connect(os.environ["DB_CONNECTION_STRING"]) as connection: - fast_wide = sys.platform == "win32" and connection.getinfo(6) == "msodbcsql18.dll" - if case in ("narrow", "overflow-row") or case.startswith("text-"): + if case in ("narrow", "overflow-row"): connection.setdecoding(ms.SQL_CHAR, encoding="cp1252", ctype=ms.SQL_CHAR) columns = ["CAST('x' AS varchar(32))"] expected = ["x"] - if case in ("wide", "narrow"): + if case in ("wide", "narrow", "compact-dense-truncated"): columns = [ "CAST(REPLICATE(CAST(NCHAR(233) AS nvarchar(max)), 8000) " "COLLATE Latin1_General_100_BIN2 AS varchar(8000))" @@ -306,15 +319,13 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, elif case == "lob": columns += ["CAST(REPLICATE(CAST(N'y' AS nvarchar(max)), 12000) AS nvarchar(max))"] expected += ["y" * 12000] - elif case.startswith("text-"): - columns = ["CAST('x' AS varchar(8000))"] - elif case == "fast-wide": + elif case == "compact-wide": columns = ["CAST('x' AS varchar(8000))"] * 8 expected = ["x"] * 8 - elif case == "fast-no-total": - columns = ["CAST(REPLICATE('x', 8000) AS varchar(8000))"] - expected = ["x" * 8000] - elif case == "fast-invalid-length": + elif case == "compact-medium": + columns = ["CAST('x' AS varchar(257))"] * 8 + expected = ["x"] * 8 + elif case.startswith("compact-"): columns = ["CAST('x' AS varchar(8000))"] sql = ( "WITH d(n) AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4)," @@ -371,14 +382,28 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, cursor.fetchall() assert not bindings assert not fetches - elif case in ("text-invalid-length", "text-truncated", "fast-invalid-length"): - message = ( - "Invalid bounded text source length" - if case == "text-invalid-length" - else "Bounded text exceeded its probed buffer size" - ) - with pytest.raises(RuntimeError, match=message): + elif case in ( + "compact-no-total", + "compact-invalid-length", + "compact-truncated", + "compact-invalid-scalar", + "compact-odd-wide-length", + "compact-dense-truncated", + ): + with pytest.raises(RuntimeError, match="Invalid bounded fetch length"): + cursor.fetchall() + if case == "compact-dense-truncated": + assert fetches == rowsets[:2] + else: + assert fetches == [rowsets[0]] + elif case in ("compact-zero-rows", "compact-excess-rows"): + with pytest.raises(RuntimeError, match="Invalid bounded fetch row count"): cursor.fetchall() + assert fetches == [rowsets[0]] + elif case == "compact-fetch-error": + with pytest.raises(ms.Error): + cursor.fetchall() + assert fetches == [rowsets[0]] elif case.endswith("-failure"): error = ( RuntimeError @@ -433,32 +458,31 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, assert tuple(sibling.fetchone()) == (42,) return - if case.startswith("text-"): - assert not bindings and not fetches - if case == "text-no-total": - size = 8001 if sys.platform == "win32" else 32001 - assert all(length == size for _, _, length in text_reads) - elif case in ("fast-wide", "fast-no-total", "fast-invalid-length"): - assert not bindings and not fetches - if case == "fast-wide": - assert len(text_reads) == count * 8 - assert len(length_probes) == (0 if fast_wide else count * 8) - elif case in ("wide", "narrow", "unicode", "mixed", "oversized-row"): - assert not bindings and not fetches - assert text_reads - # Full-width cells share one scratch allocation rather than a rowset. - if case in ("wide", "narrow", "unicode", "oversized-row"): - pointers_used = len({data for _, data, _ in text_reads}) - if fast_wide and case == "oversized-row": - assert pointers_used <= 16 - else: - assert len({data for _, data, _ in text_reads[-100:]}) == 1 - if case == "oversized-row": - assert max(length for _, _, length in text_reads) == (512 if fast_wide else 4) - elif case == "mixed": - assert max(length for ctype, _, length in text_reads if ctype == -8) == ( - 512 if fast_wide else 6 - ) + if case.startswith("compact-") or case in ( + "wide", + "narrow", + "unicode", + "mixed", + "oversized-row", + ): + assert not text_reads and not length_probes + ncols = len(columns) + 1 + first = bindings[:ncols] + row_bytes = sum(length + ct.sizeof(sql_len) for _, _, length in first) + initial = max(1, min(100, 1024 * 1024 // row_bytes)) + assert rowsets[0] == initial + assert initial * row_bytes <= 1024 * 1024 or initial == 1 + if case in ("compact-wide", "mixed", "oversized-row"): + assert all(size == initial for size in fetches) + assert len(fetches) == (count + initial - 1) // initial + 2 + elif case in ("wide", "narrow", "unicode", "compact-medium"): + target_budget = 1024 * 1024 if case == "compact-medium" else budget + target = max(1, min(1000, target_budget // row_bytes)) + assert fetches[0] == initial + assert all(size == target for size in fetches[1:-1]) + assert fetches[-1] == initial # Exhausted second fetchall. + assert rowsets[1] == target + assert bindings[ncols : 2 * ncols] == first elif ( not case.startswith("overflow-") and case != "lob" and not case.endswith("-failure") ): diff --git a/tests/test_query_cancellation.py b/tests/test_query_cancellation.py index aff476383..902584f4f 100644 --- a/tests/test_query_cancellation.py +++ b/tests/test_query_cancellation.py @@ -445,13 +445,16 @@ def _grouped_scalar_boundary_probe(kind="scalar"): ctypes.c_void_p, ) cancel_type = callback(ctypes.c_short, ctypes.c_void_p) + fetch_type = callback(ctypes.c_short, ctypes.c_void_p, ctypes.c_short, ctypes.c_ssize_t) with _connection() as connection, connection.cursor() as cursor: value = "CAST(N'text' AS nvarchar(4000))" if kind == "text" else "2" cursor.execute(f"SELECT 1, {value}, 3, 4 FROM (VALUES (1), (2)) AS source(n)") assert tuple(cursor.fetchone()) == (1, "text" if kind == "text" else 2, 3, 4) original_getdata = pointers["SQLGetData_ptr"].value + original_fetch = pointers["SQLFetchScroll_ptr"].value original_cancel = pointers["SQLCancel_ptr"].value getdata = getdata_type(original_getdata) + fetch = fetch_type(original_fetch) reads = [] @getdata_type @@ -462,6 +465,13 @@ def cancel_after_second_column(*args): cursor.cancel() return result + @fetch_type + def cancel_after_first_row(handle, orientation, offset): + reads.append("block") + result = fetch(handle, orientation, offset) + cursor.cancel() + return result + @cancel_type def cancel(_): return 0 @@ -470,9 +480,14 @@ def cancel(_): if profiling is not None: profiling.reset() profiling.enable() - pointers["SQLGetData_ptr"].value = ctypes.cast( - cancel_after_second_column, ctypes.c_void_p - ).value + if kind == "text": + pointers["SQLFetchScroll_ptr"].value = ctypes.cast( + cancel_after_first_row, ctypes.c_void_p + ).value + else: + pointers["SQLGetData_ptr"].value = ctypes.cast( + cancel_after_second_column, ctypes.c_void_p + ).value pointers["SQLCancel_ptr"].value = ctypes.cast(cancel, ctypes.c_void_p).value try: with pytest.raises(OperationalError, match="Operation canceled"): @@ -482,15 +497,16 @@ def cancel(_): cursor.fetchone() finally: pointers["SQLGetData_ptr"].value = original_getdata + pointers["SQLFetchScroll_ptr"].value = original_fetch pointers["SQLCancel_ptr"].value = original_cancel if profiling is not None: profiling.disable() - assert reads == [1, 2] + assert reads == (["block"] if kind == "text" else [1, 2]) if profiling is not None: if kind == "scalar": assert profiling.get_stats()["ddbc::SQLGetData::scalar_group"]["calls"] == 1 - elif os.name == "nt" and connection.getinfo(6) == "msodbcsql18.dll": - assert profiling.get_stats()["ddbc::SQLGetData::short_cell_group"]["calls"] == 1 + else: + assert profiling.get_stats()["ddbc::FetchReusableTextRows"]["calls"] == 1 assert cursor._query_slot.active is None assert not connection._query_state.busy assert cursor.execute("SELECT 99").fetchone()[0] == 99 From 09c272d4c246faf5d420e1dd676d4525c8095941 Mon Sep 17 00:00:00 2001 From: Jahnvi Thakkar Date: Fri, 27 Nov 2026 12:25:09 +0530 Subject: [PATCH 07/14] FIX: preserve sparse UTF-8 rowsets and avoid growth after partial fetches Correct the Unix narrow-text binding contract and cover a single full-width result without an unnecessary growth rebind. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- mssql_python/pybind/ddbc_bindings.cpp | 2 +- tests/test_017_fetch_buffer_sizing.py | 12 +++++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/mssql_python/pybind/ddbc_bindings.cpp b/mssql_python/pybind/ddbc_bindings.cpp index c14e38e21..cee2a5ce2 100644 --- a/mssql_python/pybind/ddbc_bindings.cpp +++ b/mssql_python/pybind/ddbc_bindings.cpp @@ -5706,7 +5706,7 @@ static SQLRETURN FetchReusableTextRows(const SqlHandlePtr& handle, SQLUSMALLINT bytes += static_cast(guard.storage->columns.indicators[column][row]); count += fetched; - if (!dense && count < limit) { + if (!dense && count < limit && fetched == rowArray) { dense = bytes / fetched >= boundBytes / 2; // Dense values benefit from the regular larger rowset budget. const size_t targetRows = diff --git a/tests/test_017_fetch_buffer_sizing.py b/tests/test_017_fetch_buffer_sizing.py index 9dc7c21b8..2a9721023 100644 --- a/tests/test_017_fetch_buffer_sizing.py +++ b/tests/test_017_fetch_buffer_sizing.py @@ -79,6 +79,7 @@ def test_checked_fetch_buffer_preconditions(item_size, terminator): "lob", "compact-wide", "compact-medium", + "compact-small-dense", "compact-no-total", "compact-invalid-length", "compact-truncated", @@ -155,6 +156,8 @@ def _run_case(case): count = 3 if case in ("compact-wide", "compact-medium", "compact-dense-truncated"): count = 1207 + if case == "compact-small-dense": + count = 1 def install(name, args, handler): pointer = pointers[name] @@ -325,6 +328,9 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, elif case == "compact-medium": columns = ["CAST('x' AS varchar(257))"] * 8 expected = ["x"] * 8 + elif case == "compact-small-dense": + columns = ["CAST(REPLICATE(N'x', 4000) AS nvarchar(4000))"] + expected = ["x" * 4000] elif case.startswith("compact-"): columns = ["CAST('x' AS varchar(8000))"] sql = ( @@ -472,9 +478,13 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, initial = max(1, min(100, 1024 * 1024 // row_bytes)) assert rowsets[0] == initial assert initial * row_bytes <= 1024 * 1024 or initial == 1 - if case in ("compact-wide", "mixed", "oversized-row"): + sparse_narrow = case == "narrow" and sys.platform != "win32" + if case in ("compact-wide", "compact-small-dense", "mixed", "oversized-row") or ( + sparse_narrow + ): assert all(size == initial for size in fetches) assert len(fetches) == (count + initial - 1) // initial + 2 + assert len(bindings) == 2 * ncols # Only the two fetchall invocations. elif case in ("wide", "narrow", "unicode", "compact-medium"): target_budget = 1024 * 1024 if case == "compact-medium" else budget target = max(1, min(1000, target_budget // row_bytes)) From 9ad1449fb194aadfd949ecfe81e1441833163850 Mon Sep 17 00:00:00 2001 From: Jahnvi Thakkar Date: Fri, 27 Nov 2026 14:56:24 +0530 Subject: [PATCH 08/14] TEST: cover reusable text rowset boundaries and rebind failures Exercise native zero-size fetch without consuming rows, dense fetchmany growth and tail preservation with retained converter storage, warning-bearing fetch results, and cleanup after a failed dense rebind. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/test_017_fetch_bounded_text.py | 45 +++++++++++++++++++++++++++ tests/test_017_fetch_buffer_sizing.py | 40 +++++++++++++++++++----- 2 files changed, 78 insertions(+), 7 deletions(-) diff --git a/tests/test_017_fetch_bounded_text.py b/tests/test_017_fetch_bounded_text.py index 83de9f07f..1833d9b8d 100644 --- a/tests/test_017_fetch_bounded_text.py +++ b/tests/test_017_fetch_bounded_text.py @@ -14,6 +14,51 @@ from mssql_python import SQL_CHAR, SQL_WCHAR +def test_native_zero_size_wide_fetch_preserves_pending_rows(db_connection): + from mssql_python import ddbc_bindings + + with db_connection.cursor() as cursor: + cursor.execute("SELECT CAST(N'pending' AS nvarchar(4000))") + rows = [] + assert ddbc_bindings.DDBCSQLFetchMany(cursor.hstmt, rows, 0) == 0 + assert rows == [] + assert [tuple(row) for row in cursor.fetchall()] == [("pending",)] + + +@pytest.mark.parametrize("batch_size", [101, 129]) +@pytest.mark.parametrize("narrow", [False, True], ids=["wide", "narrow"]) +def test_dense_fetchmany_growth_preserves_tail_and_converter_storage( + db_connection, batch_size, narrow +): + retained = [] + db_connection.add_output_converter( + str, lambda raw: retained.append(raw) or raw.decode("utf-16le") + ) + value = "\u00e9" * (8000 if narrow else 4000) + expression = "CAST(? AS varchar(8000))" if narrow else "CAST(? AS nvarchar(4000))" + try: + with db_connection.cursor() as cursor: + cursor.execute( + "WITH d(n) AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4)," + "(5),(6),(7),(8),(9)) AS v(n)) " + f"SELECT n, {', '.join([expression] * 8)} " + "FROM (SELECT a.n+10*b.n+100*c.n AS n " + "FROM d a CROSS JOIN d b CROSS JOIN d c) v WHERE n < 137 ORDER BY n", + (value,) * 8, + ) + first = cursor.fetchmany(batch_size) + assert len(first) == batch_size + tail = cursor.fetchall() + assert [tuple(row) for row in first + tail] == [(n,) + (value,) * 8 for n in range(137)] + assert cursor.fetchall() == [] + cursor.execute("SELECT N'reused'") + assert cursor.fetchone()[0] == "reused" + assert len(retained) == 137 * 8 + 1 + assert all(raw == value.encode("utf-16le") for raw in retained[:-1]) + finally: + db_connection.remove_output_converter(str) + + @pytest.mark.parametrize("dense_first", [False, True]) @pytest.mark.parametrize("batch_size", [None, 7, 9, 65], ids=["all", "many7", "many9", "many65"]) def test_reusable_rowsets_preserve_density_transitions(db_connection, dense_first, batch_size): diff --git a/tests/test_017_fetch_buffer_sizing.py b/tests/test_017_fetch_buffer_sizing.py index 2a9721023..786ba5425 100644 --- a/tests/test_017_fetch_buffer_sizing.py +++ b/tests/test_017_fetch_buffer_sizing.py @@ -80,6 +80,8 @@ def test_checked_fetch_buffer_preconditions(item_size, terminator): "compact-wide", "compact-medium", "compact-small-dense", + "compact-warning", + "compact-dense-rebind-failure", "compact-no-total", "compact-invalid-length", "compact-truncated", @@ -154,7 +156,12 @@ def _run_case(case): count = 2 if case in ("overflow-cell", "overflow-row", "lob") or case.startswith("compact-"): count = 3 - if case in ("compact-wide", "compact-medium", "compact-dense-truncated"): + if case in ( + "compact-wide", + "compact-medium", + "compact-dense-truncated", + "compact-dense-rebind-failure", + ): count = 1207 if case == "compact-small-dense": count = 1 @@ -177,7 +184,12 @@ def bind(original, handle, col, ctype, data, length, indicator): if case == "bind-failure" and fetches: return -2 if ( - case in ("partial-bind-failure", "partial-bind-cleanup-failure") + case + in ( + "partial-bind-failure", + "partial-bind-cleanup-failure", + "compact-dense-rebind-failure", + ) and fetches and col == 2 ): @@ -231,6 +243,8 @@ def fetch(original, handle, orientation, offset): events.append("fetch") result = original(handle, orientation, offset) if result in (0, 1): + if case == "compact-warning" and len(fetches) == 1: + return 1 # Valid bound values with SQL_SUCCESS_WITH_INFO. if case in ("compact-zero-rows", "compact-excess-rows"): output_count = ct.cast(fetched_pointer, ct.POINTER(sql_ulen)) output_count[0] = 0 if case == "compact-zero-rows" else current_size + 1 @@ -282,7 +296,7 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, connection.setdecoding(ms.SQL_CHAR, encoding="cp1252", ctype=ms.SQL_CHAR) columns = ["CAST('x' AS varchar(32))"] expected = ["x"] - if case in ("wide", "narrow", "compact-dense-truncated"): + if case in ("wide", "narrow", "compact-dense-truncated", "compact-dense-rebind-failure"): columns = [ "CAST(REPLICATE(CAST(NCHAR(233) AS nvarchar(max)), 8000) " "COLLATE Latin1_General_100_BIN2 AS varchar(8000))" @@ -414,7 +428,12 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, error = ( RuntimeError if case - in ("bind-failure", "partial-bind-failure", "partial-bind-cleanup-failure") + in ( + "bind-failure", + "partial-bind-failure", + "partial-bind-cleanup-failure", + "compact-dense-rebind-failure", + ) else ms.Error ) with pytest.raises(error) as failure: @@ -428,6 +447,9 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, assert "Failed to bind column" in str(failure.value) if case == "arrow-cleanup-failure": assert fetches == [64] + elif case == "compact-dense-rebind-failure": + assert fetches == [rowsets[0]] + assert bindings[len(columns) + 2][0] == 2 elif case not in ("persistent-rows-fetched-failure", "rowset-reset-failure"): assert fetches == [100] if case in ("partial-bind-failure", "partial-bind-cleanup-failure"): @@ -479,9 +501,13 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, assert rowsets[0] == initial assert initial * row_bytes <= 1024 * 1024 or initial == 1 sparse_narrow = case == "narrow" and sys.platform != "win32" - if case in ("compact-wide", "compact-small-dense", "mixed", "oversized-row") or ( - sparse_narrow - ): + if case in ( + "compact-wide", + "compact-small-dense", + "compact-warning", + "mixed", + "oversized-row", + ) or (sparse_narrow): assert all(size == initial for size in fetches) assert len(fetches) == (count + initial - 1) // initial + 2 assert len(bindings) == 2 * ncols # Only the two fetchall invocations. From b2e265171d6bd9b235d1b76d650efcd33c8a8be3 Mon Sep 17 00:00:00 2001 From: Jahnvi Thakkar Date: Sat, 28 Nov 2026 19:01:22 +0530 Subject: [PATCH 09/14] FIX: preserve fetchmany buffer limits with reusable rowsets Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 8 ++++++-- mssql_python/pybind/ddbc_bindings.cpp | 7 ++++++- tests/test_004_cursor.py | 9 ++++++--- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 1efbba154..161db868d 100644 --- a/README.md +++ b/README.md @@ -554,8 +554,10 @@ Wide-character retrieval of `VARCHAR(MAX)` values uses a non-consuming binary length probe to size the conversion buffer, avoiding character loss at truncated UTF-16 conversion boundaries while preserving embedded and trailing NULs. The experimental bounded-text path uses complete, reusable rowsets for `fetchall()` -and `fetchmany()` when a text column is wider than 256 declared characters, -reusing storage rather than allocating every cell at its declared width. +and `fetchmany()` when a text column is wider than 256 declared characters. +Each bound cell still reserves its complete declared width. Temporary memory +is reduced by binding fewer rows simultaneously and reusing those buffers, +not by allocating actual-length native cells. Bound storage targets 1 MiB including indicators, with at least one complete row and at most 1,000 rows (at most 100 initially). Values are decoded directly into actual-length Python results, without a second native copy or per-cell length probes. @@ -567,6 +569,8 @@ sets trade smaller rowsets and additional driver calls for lower temporary buffer use. They do not change the forward-only cursor type or recover truncated multirow bindings with `SQLGetData`. A row larger than either budget remains complete; Python results and allocator overhead are outside those targets. +`fetchmany()` retains the native 256 MiB caller-size guard based on the requested +row count and declared row width, even when reusable batches would be smaller. Result sets containing LOB columns retain their existing streaming path. The 256-character cutoff is provisional, not a tuned throughput threshold. Explicit `setinputsizes()` SQL types and sizes still take precedence. An explicit diff --git a/mssql_python/pybind/ddbc_bindings.cpp b/mssql_python/pybind/ddbc_bindings.cpp index a5001c69b..a04cf666e 100644 --- a/mssql_python/pybind/ddbc_bindings.cpp +++ b/mssql_python/pybind/ddbc_bindings.cpp @@ -6594,9 +6594,14 @@ SQLRETURN FetchMany_wrap(SqlHandlePtr StatementHandle, py::list& rows, py::handl column.columnSize > 256); } - if (dynamicText && lobColumns.empty()) + if (dynamicText && lobColumns.empty()) { + // Preserve the caller-size limit before selecting smaller reusable batches. + size_t requestedBytes = 0; + ReserveNativeFetchBytes(requestedBytes, static_cast(fetchSize), + BoundRowBufferBytes(columnNames, numCols, charCtype)); return FetchReusableTextRows(StatementHandle, numCols, rows, fetchSize, charEncoding, wcharEncoding, charCtype, messages, converters); + } if (singleRowEligible) { py::list row; diff --git a/tests/test_004_cursor.py b/tests/test_004_cursor.py index 539b603a4..91a96b31d 100644 --- a/tests/test_004_cursor.py +++ b/tests/test_004_cursor.py @@ -1780,11 +1780,14 @@ def test_executemany_rejects_text_for_binary_parameter(db_connection): cursor.executemany("SELECT CAST(? AS VARBINARY(10))", [("text",)]) -def test_fetchmany_rejects_excessive_native_buffer(cursor): - cursor.execute("SELECT CAST('x' AS VARCHAR(8000))") +@pytest.mark.parametrize("sql_type", ["VARCHAR(8000)", "NVARCHAR(4000)"]) +@pytest.mark.parametrize("column_count", [1, 8]) +def test_fetchmany_rejects_excessive_native_buffer(cursor, sql_type, column_count): + cursor.execute("SELECT " + ", ".join([f"CAST('x' AS {sql_type})"] * column_count)) with pytest.raises(RuntimeError, match="256 MiB allocation limit"): cursor.fetchmany(100_000) - assert cursor.fetchone()[0] == "x" + assert [tuple(row) for row in cursor.fetchmany(1)] == [("x",) * column_count] + assert cursor.fetchone() is None def test_fetchall_clamps_wide_result_batch_to_native_buffer_budget(cursor): From a71be3d9ae592e38b86d86201e6c74c6939ca91c Mon Sep 17 00:00:00 2001 From: Jahnvi Thakkar Date: Mon, 30 Nov 2026 11:30:31 +0530 Subject: [PATCH 10/14] TEST: restore reusable rowset binding contract assertions Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/test_017_fetch_buffer_sizing.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/test_017_fetch_buffer_sizing.py b/tests/test_017_fetch_buffer_sizing.py index 786ba5425..35645f71a 100644 --- a/tests/test_017_fetch_buffer_sizing.py +++ b/tests/test_017_fetch_buffer_sizing.py @@ -496,6 +496,19 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, assert not text_reads and not length_probes ncols = len(columns) + 1 first = bindings[:ncols] + if case in ("wide", "narrow", "unicode", "compact-wide", "compact-medium"): + assert first[0] == (1, -16, 4) # SQL_C_SLONG + if case == "narrow": + ctype = 1 # SQL_C_CHAR + capacity = 8001 if sys.platform == "win32" else 32001 + else: + ctype = -8 # SQL_C_WCHAR + declared_width = { + "unicode": 4000, + "compact-medium": 257, + }.get(case, 8000) + capacity = (declared_width + 1) * 2 + assert first[1:] == [(col, ctype, capacity) for col in range(2, ncols + 1)] row_bytes = sum(length + ct.sizeof(sql_len) for _, _, length in first) initial = max(1, min(100, 1024 * 1024 // row_bytes)) assert rowsets[0] == initial @@ -518,6 +531,9 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, assert all(size == target for size in fetches[1:-1]) assert fetches[-1] == initial # Exhausted second fetchall. assert rowsets[1] == target + first_fetch = events.index("fetch") + second_bind = events.index("bind", first_fetch + 1) + assert "unbind" in events[first_fetch + 1 : second_bind] assert bindings[ncols : 2 * ncols] == first elif ( not case.startswith("overflow-") and case != "lob" and not case.endswith("-failure") From 16c0fc0acb542e56b0ffaedfaeaf5fa2a83127ac Mon Sep 17 00:00:00 2001 From: Jahnvi Thakkar Date: Tue, 1 Dec 2026 08:34:06 +0530 Subject: [PATCH 11/14] FIX: stabilize LCOV rendering and Arrow budget regressions Normalize Python function locations without changing coverage counts, and reduce emulated SQL Server test traffic while retaining the full allocation boundary. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- eng/scripts/normalize_python_lcov.py | 33 +++++++++++ generate_codecov.sh | 3 + tests/test_004_cursor_arrow.py | 76 +++++++++++++------------ tests/test_pr_code_coverage_workflow.py | 36 ++++++++++++ tests/test_python_lcov.py | 31 ++++++++++ 5 files changed, 143 insertions(+), 36 deletions(-) create mode 100644 eng/scripts/normalize_python_lcov.py create mode 100644 tests/test_python_lcov.py diff --git a/eng/scripts/normalize_python_lcov.py b/eng/scripts/normalize_python_lcov.py new file mode 100644 index 000000000..320ecee3a --- /dev/null +++ b/eng/scripts/normalize_python_lcov.py @@ -0,0 +1,33 @@ +"""Move LCOV function starts off non-executable docstrings without changing hit counts.""" + +import argparse +from bisect import bisect_left +from pathlib import Path + + +def normalize_function_starts(report: str) -> str: + records = report.split("end_of_record") + if records[-1].strip(): + raise ValueError("Incomplete LCOV record") + normalized = [] + for record in records[:-1]: + lines = record.strip().splitlines() + executable = sorted(int(line[3:].split(",", 1)[0]) for line in lines if line.startswith("DA:")) + for index, line in enumerate(lines): + if not line.startswith("FN:"): + continue + start, end, name = line[3:].split(",", 2) + position = bisect_left(executable, int(start)) + if position == len(executable) or executable[position] > int(end): + raise ValueError(f"Function {name!r} has no executable line in its LCOV range") + lines[index] = f"FN:{executable[position]},{end},{name}" + normalized.append("\n".join([*lines, "end_of_record"])) + return "\n".join(normalized) + "\n" + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("report", type=Path) + args = parser.parse_args() + content = normalize_function_starts(args.report.read_text(encoding="utf-8")) + args.report.write_text(content, encoding="utf-8", newline="\n") diff --git a/generate_codecov.sh b/generate_codecov.sh index 7d684e2d3..b544866da 100644 --- a/generate_codecov.sh +++ b/generate_codecov.sh @@ -64,6 +64,9 @@ python -m pytest -v "$@" \ # Convert Python coverage to LCOV format (restrict to repo only) echo "[ACTION] Converting Python coverage to LCOV" coverage lcov -o python-coverage.info --include="mssql_python/*" +# coverage.py 7.18 can place FN on a docstring with no DA entry. LCOV 2.4 +# cannot categorize that location; use the first executable line in the range. +python eng/scripts/normalize_python_lcov.py python-coverage.info echo "===================================" echo "[STEP 3] Processing C++ coverage (Clang/LLVM)" diff --git a/tests/test_004_cursor_arrow.py b/tests/test_004_cursor_arrow.py index 701983d0c..3a11a0b38 100644 --- a/tests/test_004_cursor_arrow.py +++ b/tests/test_004_cursor_arrow.py @@ -39,9 +39,13 @@ import mssql_python import pyarrow.compute as pc -def wide_query(sql_type, columns, count=8192, identifiers=False, extra=""): +# Three-byte UTF-8 characters cross the Arrow byte budget with fewer ODBC rows. +ROW_COUNT = 2560 +PAYLOAD = "\\u0800" * 4000 + +def wide_query(sql_type, columns, count=ROW_COUNT, identifiers=False, extra=""): payload = ", ".join( - f"CAST(REPLICATE(N'A', 4000) AS {sql_type}) AS c{i}" for i in range(columns) + f"CAST(REPLICATE(NCHAR(2048), 4000) AS {sql_type}) AS c{i}" for i in range(columns) ) return f''' WITH digits(d) AS ( @@ -57,7 +61,7 @@ def wide_query(sql_type, columns, count=8192, identifiers=False, extra=""): def check_payload(value, columns, offset=0): for column in range(offset, offset + columns): - assert pc.all(pc.equal(value.column(column), "A" * 4000)).as_py() + assert pc.all(pc.equal(value.column(column), PAYLOAD)).as_py() """ @@ -141,10 +145,10 @@ def test_arrow_native_budget_lossless_batches(conn_str, sql_type, method, column cur.execute(wide_query(sql_type, columns)) if method == "arrow": value = cur.arrow() - assert value.num_rows == 8192 + assert value.num_rows == ROW_COUNT check_payload(value, columns) if columns == 7: - assert value.nbytes == 229841920 + assert value.nbytes == 215185600, value.nbytes else: assert value.nbytes > 256 * 1024 * 1024 assert len(value.column(0).chunks) > 1 @@ -154,10 +158,10 @@ def test_arrow_native_budget_lossless_batches(conn_str, sql_type, method, column total_bytes = 0 first = True while True: - value = cur.arrow_batch(8192) + value = cur.arrow_batch(ROW_COUNT) count = value.num_rows if first: - assert count == 8192 if columns == 7 else 0 < count < 8192 + assert count == ROW_COUNT if columns == 7 else 0 < count < ROW_COUNT first = False if not count: break @@ -167,9 +171,9 @@ def test_arrow_native_budget_lossless_batches(conn_str, sql_type, method, column assert value.nbytes <= 256 * 1024 * 1024 assert cur.rownumber == total - 1 del value - assert total == 8192 + assert total == ROW_COUNT if columns == 7: - assert total_bytes == 229841920 + assert total_bytes == 215185600, total_bytes else: assert total_bytes > 256 * 1024 * 1024 assert cur.fetchone() is None @@ -189,7 +193,7 @@ def test_arrow_native_budget_pending_mixed_fetches(conn_str, sql_type, remaining """ sql_type = sys.argv[1] remaining = sys.argv[2] - row_count = 8192 + row_count = ROW_COUNT extra = ''' , CAST('123.45' AS DECIMAL(10,2)) amount , CAST('2025-01-02' AS DATE) day @@ -200,7 +204,7 @@ def test_arrow_native_budget_pending_mixed_fetches(conn_str, sql_type, remaining ''' def check_row(row, expected): assert row[0] == expected - assert all(value == "A" * 4000 for value in row[1:10]) + assert all(value == PAYLOAD for value in row[1:10]) assert row[10] == Decimal("123.45") assert row[11] == date(2025, 1, 2) assert row[12] == UUID("58185E0D-3A91-44D8-BC46-7107217E0A6D") @@ -213,7 +217,7 @@ def check_row(row, expected): cur.execute( wide_query(sql_type, 9, count=row_count, identifiers=True, extra=extra) ) - first = cur.arrow_batch(8192) + first = cur.arrow_batch(ROW_COUNT) n = first.num_rows assert 0 < n < row_count assert first.column(0).to_pylist() == list(range(1, n + 1)) @@ -287,7 +291,7 @@ def test_arrow_native_budget_pending_scroll_skip(conn_str, sql_type): cur.execute(wide_query(sql_type, 9, identifiers=True)) first = cur.arrow_batch(8192) position = first.num_rows - assert 0 < position < 8192 + assert 0 < position < ROW_COUNT del first cur.scroll(0) cur.skip(0) @@ -319,8 +323,8 @@ def test_arrow_native_budget_pending_scroll_skip(conn_str, sql_type): position += 2 del rows assert cur.rownumber == position - 1 - cur.skip(8192 - position) - assert cur.rownumber == 8191 + cur.skip(ROW_COUNT - position) + assert cur.rownumber == ROW_COUNT - 1 assert cur.fetchone() is None try: cur.scroll(1) @@ -344,7 +348,7 @@ def test_arrow_native_budget_pending_raw_fetches(conn_str, sql_type): from mssql_python import ddbc_bindings as ddbc from mssql_python.constants import ConstantsDDBC as C sql_type = sys.argv[1] - row_count = 8192 + row_count = ROW_COUNT unsupported = ( (C.SQL_FETCH_RELATIVE.value, 0), (C.SQL_FETCH_RELATIVE.value, 1), (C.SQL_FETCH_RELATIVE.value, 67), (C.SQL_FETCH_RELATIVE.value, -1), @@ -396,7 +400,7 @@ def get_data(cur, count): assert ddbc.DDBCSQLSetStmtAttr( cur.hstmt, C.SQL_ATTR_QUERY_TIMEOUT.value, 0 ) in (0, 1) - assert get_data(cur, 3) == [position, "A" * 4000, "A" * 4000] + assert get_data(cur, 3) == [position, PAYLOAD, PAYLOAD] try: get_data(cur, 11) except RuntimeError as exc: @@ -405,7 +409,7 @@ def get_data(cur, count): raise AssertionError("Invalid prefix count was accepted") row = get_data(cur, 10) assert row[0] == position - assert row[1:] == ["A" * 4000] * 9 + assert row[1:] == [PAYLOAD] * 9 del row row = [] assert ddbc.DDBCSQLFetchScroll( @@ -413,7 +417,7 @@ def get_data(cur, count): ) in (0, 1) position += 1 assert row[0] == position - assert row[1:] == ["A" * 4000] * 9 + assert row[1:] == [PAYLOAD] * 9 del row assert cur.fetchone()[0] == position + 1 position += 1 @@ -437,7 +441,7 @@ def get_data(cur, count): ) in (0, 1) position += 1 assert row[0] == position - assert row[1:] == ["A" * 4000] * 9 + assert row[1:] == [PAYLOAD] * 9 del row # NEXT ignores its offset, and a nonempty output suppresses materialization. for offset in (0, 1, 67, -1, 123): @@ -481,7 +485,7 @@ def test_arrow_native_budget_pending_fetchall_after_raw_fetch(conn_str, sql_type from mssql_python import ddbc_bindings as ddbc from mssql_python.constants import ConstantsDDBC as C sql_type = sys.argv[1] - row_count = 8192 + row_count = ROW_COUNT with mssql_python.connect(os.environ["DB_CONNECTION_STRING"]) as conn: with conn.cursor() as cur: cur.execute(wide_query(sql_type, 9, count=row_count, identifiers=True)) @@ -498,7 +502,7 @@ def test_arrow_native_budget_pending_fetchall_after_raw_fetch(conn_str, sql_type assert row == [position] rows = cur.fetchall() assert [row[0] for row in rows] == list(range(position + 1, row_count + 1)) - assert all(all(value == "A" * 4000 for value in row[1:]) for row in rows) + assert all(all(value == PAYLOAD for value in row[1:]) for row in rows) del rows assert cur.fetchone() is None """, @@ -553,17 +557,17 @@ def test_arrow_native_budget_resumes_partial_lob(conn_str, recovery): conn_str, """ recovery = sys.argv[1] - query = wide_query("nvarchar(max)", 7, count=6002, identifiers=True) + query = wide_query("nvarchar(max)", 7, count=2002, identifiers=True) query = query.replace( - "CAST(REPLICATE(N'A', 4000) AS nvarchar(max)) AS c0", - "CASE WHEN id = 6001 THEN REPLICATE(CAST(N'A' AS nvarchar(max)), " - "40 * 1024 * 1024) ELSE CAST(REPLICATE(N'A', 4000) AS nvarchar(max)) END AS c0" + "CAST(REPLICATE(NCHAR(2048), 4000) AS nvarchar(max)) AS c0", + "CASE WHEN id = 2001 THEN REPLICATE(CAST(N'A' AS nvarchar(max)), " + "40 * 1024 * 1024) ELSE CAST(REPLICATE(NCHAR(2048), 4000) AS nvarchar(max)) END AS c0" ) with mssql_python.connect(os.environ["DB_CONNECTION_STRING"]) as conn: with conn.cursor() as cur: cur.execute(query) first = cur.arrow_batch(8192) - assert first.num_rows == 6000 + assert first.num_rows == 2000 del first if recovery != "arrow_batch": if recovery == "raw_fetch": @@ -574,22 +578,22 @@ def test_arrow_native_budget_resumes_partial_lob(conn_str, recovery): assert ddbc.DDBCSQLGetData( cur.hstmt, 1, prefix, "utf-16le", "utf-16le", C.SQL_WCHAR.value ) in (0, 1) - assert prefix == [6001] + assert prefix == [2001] row = [] assert ddbc.DDBCSQLGetData( cur.hstmt, 8, row, "utf-16le", "utf-16le", C.SQL_WCHAR.value ) in (0, 1) else: row = cur.fetchone() - assert row[0] == 6001 + assert row[0] == 2001 assert len(row[1]) == 40 * 1024 * 1024 assert row[1].count("A") == len(row[1]) - assert all(value == "A" * 4000 for value in row[2:]) + assert all(value == PAYLOAD for value in row[2:]) del row - assert cur.fetchone()[0] == 6002 + assert cur.fetchone()[0] == 2002 else: batch = cur.arrow_batch(8192) - assert batch.column(0).to_pylist() == [6001, 6002] + assert batch.column(0).to_pylist() == [2001, 2002] value = batch.column(1)[0].as_py() assert len(value) == 40 * 1024 * 1024 assert value.count("A") == len(value) @@ -660,7 +664,7 @@ def test_arrow_native_budget_pending_reset_cleanup(conn_str, sql_type, operation """ sql_type = sys.argv[1] operation = sys.argv[2] - row_count = 8192 + row_count = ROW_COUNT with mssql_python.connect(os.environ["DB_CONNECTION_STRING"]) as conn: with conn.cursor() as cur: cur.execute(wide_query(sql_type, 9, count=row_count) + "; SELECT 42 AS answer") @@ -707,7 +711,7 @@ def fetch_after_change(generic): with conn.cursor() as cur: cur.execute(wide_query(sql_type, 9, identifiers=True)) first = cur.arrow_batch(8192) - assert 0 < first.num_rows < 8192 + assert 0 < first.num_rows < ROW_COUNT del first if generic: conn._conn.set_attr( @@ -749,7 +753,7 @@ def test_arrow_native_budget_idempotent_autocommit_preserves_rows(conn_str, auto cur.execute(wide_query("nvarchar(4000)", 9, identifiers=True)) first = cur.arrow_batch(8192) count = first.num_rows - assert 0 < count < 8192 + assert 0 < count < ROW_COUNT assert first.column(0).to_pylist() == list(range(1, count + 1)) del first @@ -762,7 +766,7 @@ def test_arrow_native_budget_idempotent_autocommit_preserves_rows(conn_str, auto while rows := cur.fetchmany(64): assert [row[0] for row in rows] == list(range(next_id, next_id + len(rows))) next_id += len(rows) - assert next_id == 8193 + assert next_id == ROW_COUNT + 1 """, str(autocommit), ) diff --git a/tests/test_pr_code_coverage_workflow.py b/tests/test_pr_code_coverage_workflow.py index 9f116b6db..eaf9e881c 100644 --- a/tests/test_pr_code_coverage_workflow.py +++ b/tests/test_pr_code_coverage_workflow.py @@ -26,6 +26,42 @@ } +def test_python_lcov_function_docstrings_render(tmp_path): + if not shutil.which("genhtml"): + pytest.skip("requires genhtml") + source = tmp_path / "example.py" + source.write_text( + 'def covered():\n """Covered function."""\n return 42\n\n' + 'def uncovered():\n """Uncovered function."""\n return 0\n\ncovered()\n', + encoding="utf-8", + ) + for args in ( + ["coverage", "run", "--rcfile=/dev/null", str(source)], + ["coverage", "lcov", "--rcfile=/dev/null", "-o", "python.info"], + ): + subprocess.run([sys.executable, "-m", *args], cwd=tmp_path, check=True, capture_output=True) + report = (tmp_path / "python.info").read_text(encoding="utf-8") + for record in ("LF:5", "LH:4", "FNF:2", "FNH:1"): + assert record in report.splitlines() + normalizer = WORKFLOW.parents[2] / "eng" / "scripts" / "normalize_python_lcov.py" + subprocess.run( + [sys.executable, str(normalizer), str(tmp_path / "python.info")], + check=True, + capture_output=True, + ) + normalized = (tmp_path / "python.info").read_text(encoding="utf-8") + assert [line for line in report.splitlines() if not line.startswith("FN:")] == [ + line for line in normalized.splitlines() if not line.startswith("FN:") + ] + subprocess.run( + ["genhtml", "python.info", "--output-directory", "html", "--quiet"], + cwd=tmp_path, + check=True, + capture_output=True, + ) + assert (tmp_path / "html" / "index.html").is_file() + + def _build(build_id=174262, sha=SHA, pr="779", branch="refs/pull/779/merge", definition=2128): return { "id": build_id, diff --git a/tests/test_python_lcov.py b/tests/test_python_lcov.py new file mode 100644 index 000000000..b3c10d249 --- /dev/null +++ b/tests/test_python_lcov.py @@ -0,0 +1,31 @@ +"""LCOV function-location compatibility without altering measured coverage.""" + +import pytest + +from eng.scripts.normalize_python_lcov import normalize_function_starts + + +def test_docstring_function_starts_use_executable_lines(): + report = ( + "SF:example.py\nDA:1,1\nDA:3,1\nDA:5,1\nDA:7,0\n" + "FN:2,3,covered\nFNDA:1,covered\nFN:6,7,uncovered\nFNDA:0,uncovered\n" + "FNF:2\nFNH:1\nLF:4\nLH:3\nend_of_record\n" + "SF:other.py\nDA:10,1\nFN:10,10,other\nFNDA:1,other\nend_of_record\n" + ) + normalized = normalize_function_starts(report) + assert "FN:3,3,covered\n" in normalized + assert "FN:7,7,uncovered\n" in normalized + assert "FN:10,10,other\n" in normalized + assert [line for line in report.splitlines() if not line.startswith("FN:")] == [ + line for line in normalized.splitlines() if not line.startswith("FN:") + ] + assert normalize_function_starts(normalized) == normalized + + +@pytest.mark.parametrize( + "report", + ["SF:example.py\nDA:1,1\n", "SF:example.py\nDA:1,1\nFN:2,3,missing\nend_of_record\n"], +) +def test_invalid_function_reports_fail_explicitly(report): + with pytest.raises(ValueError): + normalize_function_starts(report) From 4e604a49df9cc0e608aa9ad0971eb0725609bee5 Mon Sep 17 00:00:00 2001 From: Jahnvi Thakkar Date: Tue, 1 Dec 2026 11:21:44 +0530 Subject: [PATCH 12/14] DOC: clarify bounded-rowset memory and throughput tradeoff Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 161db868d..c30d29ef7 100644 --- a/README.md +++ b/README.md @@ -566,7 +566,17 @@ can grow once to the ordinary 8 MiB rowset budget. Every driver fetch retains cancellation and diagnostic handling; rebinding preserves cleanup lifetimes. Fixed-width and short-text result sets retain rowset batching. Wide-text result sets trade smaller rowsets and additional driver calls for lower temporary -buffer use. They do not change the forward-only cursor type or recover truncated +buffer use, not demonstrated throughput improvement. More batches also repeat +conversion-metadata setup and, until dense growth, indicator scans. +For a historical Windows observation of 5,000 rows with an integer ID and eight +short values declared `VARCHAR(8000)`, bound data plus indicators fell from about +7.94 MiB to 0.98 MiB, while driver fetch calls rose from 78 to 626. +These are driver-call counts, not measured network round trips; they do not +establish production latency on the current revision. Profiling-enabled CI +reports are attribution evidence, and a "no signal" result does not rule out +smaller slowdowns. Repeated, matched, profiling-disabled measurements are needed +before claiming a throughput benefit or no regression. +The rowsets do not change the forward-only cursor type or recover truncated multirow bindings with `SQLGetData`. A row larger than either budget remains complete; Python results and allocator overhead are outside those targets. `fetchmany()` retains the native 256 MiB caller-size guard based on the requested From 4cdb5aa2bb951f78e1c1b8868081d3ca3f8f0494 Mon Sep 17 00:00:00 2001 From: Jahnvi Thakkar Date: Tue, 1 Dec 2026 13:11:34 +0530 Subject: [PATCH 13/14] PERF: reuse bounded-rowset conversion metadata Prepare column conversion metadata once per reusable-rowset call and avoid unnecessary density scans while retaining existing rowset budgets and full-width bindings. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 6 +- mssql_python/pybind/ddbc_bindings.cpp | 80 +++++++++++++++------------ tests/test_025_profiler.py | 30 ++++++++++ 3 files changed, 78 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index c30d29ef7..71895f664 100644 --- a/README.md +++ b/README.md @@ -566,8 +566,10 @@ can grow once to the ordinary 8 MiB rowset budget. Every driver fetch retains cancellation and diagnostic handling; rebinding preserves cleanup lifetimes. Fixed-width and short-text result sets retain rowset batching. Wide-text result sets trade smaller rowsets and additional driver calls for lower temporary -buffer use, not demonstrated throughput improvement. More batches also repeat -conversion-metadata setup and, until dense growth, indicator scans. +buffer use, not demonstrated throughput improvement. Conversion metadata and +processor dispatch are prepared once per native reusable-rowset call, including +across buffer growth. Density scans only inspect full batches that can grow and +stop once the dense threshold is reached; sparse batches may still require scans. For a historical Windows observation of 5,000 rows with an integer ID and eight short values declared `VARCHAR(8000)`, bound data plus indicators fell from about 7.94 MiB to 0.98 MiB, while driver fetch calls rose from 78 to 626. diff --git a/mssql_python/pybind/ddbc_bindings.cpp b/mssql_python/pybind/ddbc_bindings.cpp index a04cf666e..296e3ecf6 100644 --- a/mssql_python/pybind/ddbc_bindings.cpp +++ b/mssql_python/pybind/ddbc_bindings.cpp @@ -5909,21 +5909,7 @@ void ValidateArrowFetchedRowCount(SQLULEN numRowsFetched, int currentFetchSize, } } -// Fetch rows in batches -// TODO: Move to anonymous namespace, since it is not used outside this file -template -SQLRETURN ConvertBufferedRows(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& columnNames, - py::list& rows, SQLUSMALLINT numCols, SQLULEN& numRowsFetched, - const std::vector& lobColumns, - const std::string& charEncoding = "utf-16le", int charCtype = SQL_C_WCHAR, - py::handle messages = {}, py::handle converters = {}, SQLULEN firstRow = 0, - int bufferRows = 0) { - // Pre-cache column metadata to avoid repeated dictionary lookups. - // The vectors below are consumed later by construct_rows, so they are - // declared at function scope; only the population work is wrapped in the - // cache_column_metadata timer's block (an earlier version put the timer at - // function scope, so it stayed active through construct_rows and made - // metadata caching look like a dominant fetch cost). +struct BufferedRowConversion { struct ColumnInfo { SQLSMALLINT dataType; SQLULEN columnSize; @@ -5933,18 +5919,33 @@ SQLRETURN ConvertBufferedRows(SQLHSTMT hStmt, ColumnBuffers& buffers, const Meta size_t fixedValueSize; bool isLob; }; - const bool useWideChar = (charCtype == SQL_C_WCHAR); - std::vector columnInfos(numCols); - // Performance: Build function pointer dispatch table (once per batch). - // This eliminates the switch statement from the hot loop - 10,000 rows × 10 - // cols reduces from 100,000 switch evaluations to just 10 switch evaluations. - std::vector columnProcessors(numCols); - std::vector columnInfosExt(numCols); - // Compute effective char encoding once for the batch (same for all columns) - const std::string effectiveCharEnc = GetEffectiveCharDecoding(charEncoding); + std::vector columnInfos; + std::vector columnProcessors; + std::vector columnInfosExt; + bool prepared = false; +}; - { +// Fetch rows in batches +// TODO: Move to anonymous namespace, since it is not used outside this file +template +SQLRETURN ConvertBufferedRows(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& columnNames, + py::list& rows, SQLUSMALLINT numCols, SQLULEN& numRowsFetched, + const std::vector& lobColumns, + const std::string& charEncoding = "utf-16le", int charCtype = SQL_C_WCHAR, + py::handle messages = {}, py::handle converters = {}, SQLULEN firstRow = 0, + int bufferRows = 0, BufferedRowConversion* reusableConversion = nullptr) { + BufferedRowConversion localConversion; + auto& conversion = reusableConversion ? *reusableConversion : localConversion; + auto& columnInfos = conversion.columnInfos; + auto& columnProcessors = conversion.columnProcessors; + auto& columnInfosExt = conversion.columnInfosExt; + if (!conversion.prepared) { PERF_TIMER("FetchBatchData::cache_column_metadata"); + const bool useWideChar = (charCtype == SQL_C_WCHAR); + const std::string effectiveCharEnc = GetEffectiveCharDecoding(charEncoding); + columnInfos.resize(numCols); + columnProcessors.resize(numCols); + columnInfosExt.resize(numCols); for (SQLUSMALLINT col = 0; col < numCols; col++) { const auto& columnMeta = GetFetchColumnMetadata(columnNames, col); columnInfos[col].dataType = GetFetchColumnType(columnMeta); @@ -6051,7 +6052,8 @@ SQLRETURN ConvertBufferedRows(SQLHSTMT hStmt, ColumnBuffers& buffers, const Meta break; } } - } // end cache_column_metadata timer scope + conversion.prepared = true; + } // Performance: Single-phase row creation pattern // Create each row, fill it completely, then append to results list @@ -6289,7 +6291,8 @@ SQLRETURN FetchBatchData(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& const std::vector& lobColumns, const std::string& charEncoding = "utf-16le", int charCtype = SQL_C_WCHAR, py::handle messages = {}, py::handle converters = {}, - size_t maximumRows = 0) { + size_t maximumRows = 0, + BufferedRowConversion* reusableConversion = nullptr) { PERF_TIMER("FetchBatchData"); LOG("FetchBatchData: Fetching data in batches"); SQLRETURN ret; @@ -6307,7 +6310,8 @@ SQLRETURN FetchBatchData(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& ThrowStdException("Invalid bounded fetch row count"); } ConvertBufferedRows(hStmt, buffers, columnNames, rows, numCols, numRowsFetched, - lobColumns, charEncoding, charCtype, messages, converters); + lobColumns, charEncoding, charCtype, messages, converters, + 0, 0, reusableConversion); return ret; } @@ -6455,6 +6459,9 @@ static SQLRETURN FetchReusableTextRows(const SqlHandlePtr& handle, SQLUSMALLINT guard.observe(ret); guard.configure(boundRows); size_t configuredRows = boundRows; + // Strides and conversion settings stay fixed across complete-cell rebindings. + // Keep this plan local to the call; it owns no pointers into bound storage. + BufferedRowConversion conversion; bool dense = false; for (size_t count = 0; count < limit;) { const size_t rowArray = std::min(boundRows, limit - count); @@ -6464,23 +6471,24 @@ static SQLRETURN FetchReusableTextRows(const SqlHandlePtr& handle, SQLUSMALLINT } ret = FetchBatchData(statement, guard.storage->columns, columns, rows, numCols, guard.storage->rowsFetched, {}, charEncoding, charCtype, messages, - converters, rowArray); + converters, rowArray, &conversion); CheckFetchError(handle, ret); if (ret == SQL_NO_DATA) break; if (!SQL_SUCCEEDED(ret)) return ret; const size_t fetched = guard.storage->rowsFetched; - size_t bytes = 0; - if (!dense) - for (size_t column = 0; column < numCols; ++column) - for (size_t row = 0; row < fetched; ++row) + count += fetched; + if (!dense && count < limit && fetched == rowArray) { + const size_t denseBytes = + CheckedMultiplySize(fetched, boundBytes / 2, "Fetch density size is too large"); + size_t bytes = 0; + for (size_t column = 0; column < numCols && bytes < denseBytes; ++column) + for (size_t row = 0; row < fetched && bytes < denseBytes; ++row) if (guard.storage->columns.indicators[column][row] >= 0) bytes += static_cast(guard.storage->columns.indicators[column][row]); - count += fetched; - if (!dense && count < limit && fetched == rowArray) { - dense = bytes / fetched >= boundBytes / 2; + dense = bytes >= denseBytes; // Dense values benefit from the regular larger rowset budget. const size_t targetRows = dense ? std::clamp(denseBudget / boundBytes, 1, maximumRows) : sparseRows; diff --git a/tests/test_025_profiler.py b/tests/test_025_profiler.py index 1db0ebce1..a6c7d33ab 100644 --- a/tests/test_025_profiler.py +++ b/tests/test_025_profiler.py @@ -394,6 +394,36 @@ def test_cpp_profiling_captures_query(): assert sample["calls"] >= 1 +@_needs_cpp +@_needs_db +@pytest.mark.parametrize("fetch_size", [None, 129], ids=["fetchall", "fetchmany"]) +@pytest.mark.parametrize("dense", [False, True]) +def test_reusable_fetch_prepares_conversion_once_per_call(db_connection, fetch_size, dense): + value = "x" * 3998 + "\U0001f642" if dense else "short" + sql = ( + "WITH d(n) AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4)," + "(5),(6),(7),(8),(9)) v(n)) " + "SELECT n, " + + ", ".join(["CAST(? AS NVARCHAR(4000))"] * 8) + + " FROM (SELECT a.n+10*b.n+100*c.n AS n FROM d a CROSS JOIN d b CROSS JOIN d c) v " + "WHERE n < 137 ORDER BY n" + ) + with db_connection.cursor() as cursor: + for expected in (value, "different"): + cursor.execute(sql, (expected,) * 8) + ddbc.profiling.reset() + ddbc.profiling.enable() + try: + rows = cursor.fetchall() if fetch_size is None else cursor.fetchmany(fetch_size) + finally: + ddbc.profiling.disable() + stats = ddbc.profiling.get_stats() + count = 137 if fetch_size is None else fetch_size + assert [tuple(row) for row in rows] == [(n,) + (expected,) * 8 for n in range(count)] + assert stats["ddbc::FetchBatchData::SQLFetchScroll_call"]["calls"] > 1 + assert stats["ddbc::FetchBatchData::cache_column_metadata"]["calls"] == 1 + + @_needs_cpp @_needs_db def test_cpp_timeline_captures_events(): From 715a812a010051779f0c13d8370bf66f0cb8f0a0 Mon Sep 17 00:00:00 2001 From: Jahnvi Thakkar Date: Tue, 1 Dec 2026 14:05:20 +0530 Subject: [PATCH 14/14] PERF: restore sustained batching after small text fetch startup Grow once to the ordinary rowset target after a full initial batch, remove density scans, and assert bounded startup storage and sustained driver-call counts. Document the remaining memory and latency tradeoffs. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 33 +++++++------ mssql_python/pybind/ddbc_bindings.cpp | 33 +++++-------- tests/test_017_fetch_buffer_sizing.py | 67 ++++++++++++++++++--------- 3 files changed, 75 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index 71895f664..2099df002 100644 --- a/README.md +++ b/README.md @@ -558,22 +558,27 @@ and `fetchmany()` when a text column is wider than 256 declared characters. Each bound cell still reserves its complete declared width. Temporary memory is reduced by binding fewer rows simultaneously and reusing those buffers, not by allocating actual-length native cells. -Bound storage targets 1 MiB including indicators, with at least one complete row -and at most 1,000 rows (at most 100 initially). Values are decoded directly into -actual-length Python results, without a second native copy or per-cell length probes. -When observed payload occupies at least half the declared row width, storage -can grow once to the ordinary 8 MiB rowset budget. Every driver fetch retains +Initial bound storage targets 1 MiB including indicators, with at least one +complete row and at most 100 rows. After the first full batch the row capacity +can grow once to the ordinary 8 MiB target and 1,000 rows. Partial batches do not +trigger growth, and `fetchmany()` never grows beyond its remaining requested rows. +Values are decoded directly into actual-length Python results, without a second +native copy or per-cell length probes. Every driver fetch retains cancellation and diagnostic handling; rebinding preserves cleanup lifetimes. Fixed-width and short-text result sets retain rowset batching. Wide-text result -sets trade smaller rowsets and additional driver calls for lower temporary -buffer use, not demonstrated throughput improvement. Conversion metadata and -processor dispatch are prepared once per native reusable-rowset call, including -across buffer growth. Density scans only inspect full batches that can grow and -stop once the dense threshold is reached; sparse batches may still require scans. -For a historical Windows observation of 5,000 rows with an integer ID and eight -short values declared `VARCHAR(8000)`, bound data plus indicators fell from about -7.94 MiB to 0.98 MiB, while driver fetch calls rose from 78 to 626. -These are driver-call counts, not measured network round trips; they do not +sets save temporary storage at startup and for short results, not throughout +large sparse `fetchall()` results: sustained fetching grows to the normal 8 MiB +target rather than imposing a persistently higher driver-call count. +For `fetchmany()`, that target can still save storage compared with binding the +entire requested row count, but can require multiple driver fetches. +Conversion metadata and processor dispatch are prepared once per native +reusable-rowset call, including +across buffer growth. No per-cell density scan is needed. +The earlier fixed-small-rowset experiment used 0.98 MiB instead of 7.94 MiB for +5,000 rows with an integer ID and eight short values declared `VARCHAR(8000)`, +but increased fetch calls from 78 to 626. The growth policy intentionally gives +up that sustained memory reduction to restore useful batching. +Driver-call counts are not measured network round trips; they do not establish production latency on the current revision. Profiling-enabled CI reports are attribution evidence, and a "no signal" result does not rule out smaller slowdowns. Repeated, matched, profiling-disabled measurements are needed diff --git a/mssql_python/pybind/ddbc_bindings.cpp b/mssql_python/pybind/ddbc_bindings.cpp index 296e3ecf6..3c4ec1739 100644 --- a/mssql_python/pybind/ddbc_bindings.cpp +++ b/mssql_python/pybind/ddbc_bindings.cpp @@ -6428,8 +6428,8 @@ struct FetchStateGuard { } }; -// Decode complete cells directly from a small reusable rowset. Python results -// own actual-length values; no truncated binding or SQLGetData recovery is needed. +// Start with a small rowset, then use normal batching after the first complete batch. +// Full-width bindings preserve values without SQLGetData recovery or cursor changes. static SQLRETURN FetchReusableTextRows(const SqlHandlePtr& handle, SQLUSMALLINT numCols, py::list& rows, size_t limit, const std::string& charEncoding, @@ -6444,12 +6444,14 @@ static SQLRETURN FetchReusableTextRows(const SqlHandlePtr& handle, SQLUSMALLINT ThrowStdException("Column metadata count does not match result column count"); const auto& columns = metadata->columns; constexpr size_t maximumRows = 1000; - constexpr size_t denseBudget = size_t{8} * 1024 * 1024; - constexpr size_t bindingBudget = size_t{1} * 1024 * 1024; + constexpr size_t maximumBudget = size_t{8} * 1024 * 1024; + constexpr size_t initialBudget = size_t{1} * 1024 * 1024; const size_t boundBytes = BoundRowBufferBytes(columns, numCols, charCtype); - const size_t sparseRows = - std::min(limit, std::clamp(bindingBudget / boundBytes, 1, maximumRows)); - size_t boundRows = std::min(sparseRows, size_t{100}); + const size_t maximumBatchRows = + std::clamp(maximumBudget / boundBytes, 1, maximumRows); + const size_t initialBatchRows = + std::clamp(initialBudget / boundBytes, 1, maximumBatchRows); + size_t boundRows = std::min({limit, size_t{100}, initialBatchRows}); FetchStateGuard guard(handle, messages, numCols, static_cast(boundRows)); SQLHSTMT statement = handle->get(); size_t reservedBytes = 0; @@ -6462,7 +6464,6 @@ static SQLRETURN FetchReusableTextRows(const SqlHandlePtr& handle, SQLUSMALLINT // Strides and conversion settings stay fixed across complete-cell rebindings. // Keep this plan local to the call; it owns no pointers into bound storage. BufferedRowConversion conversion; - bool dense = false; for (size_t count = 0; count < limit;) { const size_t rowArray = std::min(boundRows, limit - count); if (rowArray != configuredRows) { @@ -6479,20 +6480,8 @@ static SQLRETURN FetchReusableTextRows(const SqlHandlePtr& handle, SQLUSMALLINT return ret; const size_t fetched = guard.storage->rowsFetched; count += fetched; - if (!dense && count < limit && fetched == rowArray) { - const size_t denseBytes = - CheckedMultiplySize(fetched, boundBytes / 2, "Fetch density size is too large"); - size_t bytes = 0; - for (size_t column = 0; column < numCols && bytes < denseBytes; ++column) - for (size_t row = 0; row < fetched && bytes < denseBytes; ++row) - if (guard.storage->columns.indicators[column][row] >= 0) - bytes += - static_cast(guard.storage->columns.indicators[column][row]); - dense = bytes >= denseBytes; - // Dense values benefit from the regular larger rowset budget. - const size_t targetRows = - dense ? std::clamp(denseBudget / boundBytes, 1, maximumRows) : sparseRows; - const size_t batchRows = std::min(limit - count, targetRows); + if (count < limit && fetched == rowArray && boundRows < maximumBatchRows) { + const size_t batchRows = std::min(limit - count, maximumBatchRows); if (batchRows <= boundRows) continue; guard.observe(SQLFreeStmt_ptr(statement, SQL_UNBIND)); diff --git a/tests/test_017_fetch_buffer_sizing.py b/tests/test_017_fetch_buffer_sizing.py index 35645f71a..2a104d058 100644 --- a/tests/test_017_fetch_buffer_sizing.py +++ b/tests/test_017_fetch_buffer_sizing.py @@ -78,6 +78,9 @@ def test_checked_fetch_buffer_preconditions(item_size, terminator): "repeat-cleanup", "lob", "compact-wide", + "compact-large", + "compact-boundary", + "compact-partial", "compact-medium", "compact-small-dense", "compact-warning", @@ -165,6 +168,10 @@ def _run_case(case): count = 1207 if case == "compact-small-dense": count = 1 + if case == "compact-large": + count = 5000 + if case in ("compact-boundary", "compact-partial"): + count = 8 if case == "compact-boundary" else 7 def install(name, args, handler): pointer = pointers[name] @@ -336,7 +343,7 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, elif case == "lob": columns += ["CAST(REPLICATE(CAST(N'y' AS nvarchar(max)), 12000) AS nvarchar(max))"] expected += ["y" * 12000] - elif case == "compact-wide": + elif case in ("compact-wide", "compact-large", "compact-boundary", "compact-partial"): columns = ["CAST('x' AS varchar(8000))"] * 8 expected = ["x"] * 8 elif case == "compact-medium": @@ -486,7 +493,14 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, assert tuple(sibling.fetchone()) == (42,) return - if case.startswith("compact-") or case in ( + if case in ( + "compact-wide", + "compact-large", + "compact-boundary", + "compact-partial", + "compact-medium", + "compact-small-dense", + "compact-warning", "wide", "narrow", "unicode", @@ -513,30 +527,39 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, initial = max(1, min(100, 1024 * 1024 // row_bytes)) assert rowsets[0] == initial assert initial * row_bytes <= 1024 * 1024 or initial == 1 - sparse_narrow = case == "narrow" and sys.platform != "win32" - if case in ( - "compact-wide", - "compact-small-dense", - "compact-warning", - "mixed", - "oversized-row", - ) or (sparse_narrow): - assert all(size == initial for size in fetches) - assert len(fetches) == (count + initial - 1) // initial + 2 - assert len(bindings) == 2 * ncols # Only the two fetchall invocations. - elif case in ("wide", "narrow", "unicode", "compact-medium"): - target_budget = 1024 * 1024 if case == "compact-medium" else budget - target = max(1, min(1000, target_budget // row_bytes)) - assert fetches[0] == initial - assert all(size == target for size in fetches[1:-1]) - assert fetches[-1] == initial # Exhausted second fetchall. - assert rowsets[1] == target + target = max(1, min(1000, budget // row_bytes)) + expected_fetches = [] + expected_bindings = [initial] + remaining = count + size = initial + while True: + expected_fetches.append(size) + fetched = min(remaining, size) + remaining -= fetched + if not fetched: + break + if fetched == size and size < target: + size = target + expected_bindings.append(size) + expected_fetches.append(initial) # Exhausted second fetchall. + assert fetches == expected_fetches + assert len(bindings) == (len(expected_bindings) + 1) * ncols + for index in range(len(expected_bindings) + 1): + assert bindings[index * ncols : (index + 1) * ncols] == first + if len(expected_bindings) > 1: + assert rowsets[: len(expected_bindings)] == expected_bindings first_fetch = events.index("fetch") second_bind = events.index("bind", first_fetch + 1) assert "unbind" in events[first_fetch + 1 : second_bind] - assert bindings[ncols : 2 * ncols] == first + if case == "compact-large": + # Ordinary 8 MiB batching needs 78 calls for this shape. + # Small startup adds one, not the previous 548 extra calls. + assert len(fetches) - 1 == 79 + assert all(size * row_bytes <= budget or size == 1 for size in fetches) elif ( - not case.startswith("overflow-") and case != "lob" and not case.endswith("-failure") + not case.startswith(("overflow-", "compact-")) + and case != "lob" + and not case.endswith("-failure") ): ncols = len(columns) + 1 first = bindings[:ncols]