Skip to content

PERF: reduce bounded-text rowset memory - #920

Open
Jahnvi Thakkar (jahnvi480) wants to merge 19 commits into
mainfrom
jahnvi/dynamic-string-fetch-buffers
Open

Jahnvi Thakkar (jahnvi480) wants to merge 19 commits into
mainfrom
jahnvi/dynamic-string-fetch-buffers

Conversation

@jahnvi480

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

Copy link
Copy Markdown
Contributor

Work Item / Issue Reference

N/A

GitHub Issue: #455


Summary

Reduce temporary native bound storage for wide-declared text using smaller complete reusable rowsets. This is a memory/driver-call tradeoff, not a demonstrated throughput improvement. Each bound cell still reserves its declared width; fewer rows are bound simultaneously. Python result memory is outside the native rowset target.

  • Eligible fetchall()/fetchmany() results contain bounded text wider than 256 declared characters and no LOB/variant columns. Target 1 MiB of bound data plus indicators, at most 100 initial rows and 1,000 later, retaining at least one complete row.
  • Decode directly into actual-length Python results. No extra compact native copy, per-cell length probes, unsupported truncated-rowset recovery, or cursor-type changes. The removed per-cell prototype is no longer the implementation under review.
  • Full rowsets whose observed payload reaches half the declared row width can grow to the ordinary 8 MiB target. Sparse data keeps the smaller target.
  • Preserve checked allocation limits, invalid-length/row-count rejection, failed-cleanup lifetimes, cancellation, diagnostics, output-converter ownership, Unicode/astral and CP1252 fidelity, embedded NULs, NULL/empty values, and pending Arrow rows.
  • CI follow-ups normalize Python LCOV function locations without changing coverage hit counts, and reduce Arrow test ODBC traffic while retaining real 256 MiB budget crossings.

Review clarification (4e604a49): More batches mean more driver fetch calls, repeated conversion-metadata setup, and indicator scans until dense growth. The README now makes these costs explicit. No production algorithm or budget was changed in response to this comment, and no new latency measurement is claimed.

Historical evidence, not current-head production latency: For 5,000 rows with an integer ID and eight short values declared VARCHAR(8000), the reusable-rowset implementation used about 0.98 MiB of bound data plus indicators versus 7.94 MiB on pinned main, with 626 versus 78 SQLFetchScroll calls (about 88% less bound storage and 8 times as many fetch calls). These are driver calls, not measured network round trips. The removed per-cell prototype made 5,001 SQLFetch plus 45,000 SQLGetData calls; that comparison establishes removal of the prototype bottleneck, not superiority over main.

The 2026-11-27 profiling-disabled Windows comparisons used candidate 2068695b0f268485836fe8e3cd672810719b1060 and base cfd8b9e69699e5e44d7c1d62115dd8b706ac7985, Python 3.13.17, matching MSVC Release builds, SQL Server 15.0.4382.1, and the same ODBC driver DLL. Six counterbalanced fresh-process rounds excluded execute, GC, verification and cleanup from fetch timing. The materialized 50,000-row workload had main/candidate medians 124.56/130.18 ms (candidate 4.5% slower) with substantial variability. Generated-query and materialized results were inconsistent, and unchanged controls also varied. These observations belong to that earlier revision; current-head throughput readiness has not been established. Advisory whole-process memory samples from the earlier implementation are not exact allocation peaks; retained Python results and allocator behavior are outside the bound-storage comparison.

The automated CI performance report uses profiling-enabled builds for attribution. Its detector requires more than 20% median paired movement plus additional consistency conditions. A "no signal" result is not proof of equivalent production-wheel latency and cannot exclude smaller regressions. Repeated, matched, profiling-disabled measurements on the actual candidate and base are required before claiming a throughput benefit or no regression. The 256-character threshold and 1 MiB policy remain experimental.

Validation and limits:

  • Before the documentation-only follow-up: cmake --build mssql_python\pybind\build\x64\py313 --config Release - passed with the worktree development interpreter and VS 2022 environment, profiling OFF and test interposition ON.
  • .\.venv\Scripts\python.exe -m pytest tests\test_004_cursor_arrow.py tests\test_017_fetch_buffer_sizing.py tests\test_python_lcov.py --cov=mssql_python --cov-report= -q --disable-warnings --tb=short - 171 passed, 1 skipped, 1 deselected during the CI fix; after the final Arrow workload adjustment, .\.venv\Scripts\python.exe -m pytest tests\test_004_cursor_arrow.py -k 'native_budget' -q --disable-warnings --tb=short - 42 passed, 87 deselected.
  • Reproduced the exact coverage.py 7.18 / LCOV 2.4 unexpected category UNK renderer failure in an isolated Linux container. Normalization rendered successfully with unchanged line/function hit totals and no ignored errors; python3 -m pytest /repo/tests/test_python_lcov.py /repo/tests/test_pr_code_coverage_workflow.py -q - 21 passed there.
  • .\.venv\Scripts\python.exe -m pre_commit run black-check --all-files --hook-stage pre-push - passed for the documentation commit; commit/push hooks and git diff --check passed.
  • No new runtime tests or latency benchmarks for the documentation-only commit. Hosted CI is separate; no claim that the new head is green. Current-head profiling-disabled A/B measurements, production/WAN behavior, alternative providers and local macOS/ARM64 runtime validation remain unverified. Earlier isolated pool/fetch fidelity suites passed; a combined pool-state ordering failure also reproduced on pinned main and was not changed here.

Historical raw observations and provenance remain in the originating session artifacts: reusable-unsampled-comparison.jsonl, reusable-unsampled-report.json, reusable-materialized-comparison.jsonl, reusable-materialized-report.json, reusable-final-driver-counts.json, and matching build/test logs. Benchmark artifacts and native binaries are not committed. Superseded per-revision validation detail remains in the PR history rather than being presented as fresh evidence.

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>
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>
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>
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>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@github-actions github-actions Bot added the pr-size: large Substantial code update label Nov 26, 2026
@jahnvi480
Jahnvi Thakkar (jahnvi480) changed the base branch from jahnvi/issue-455-reduce-fetch-buffer-over-allocation-2aa932 to main November 27, 2026 05:01
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

PR Performance Report

Performance assessment pending.

Waiting for the matching performance run for head 5790f79be6bbc92fd7c00174755c6d2cc0318dd1.

@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

📊 Code Coverage Report

🔥 Diff Coverage

76%


🎯 Overall Coverage

87%


📈 Total Lines Covered: 15261 out of 17486
📁 Project: mssql-python


Diff Coverage

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

  • mssql_python/pybind/ddbc_bindings.cpp (76.5%): Missing lines 4651,4690-4691,5884-5885,5928-5930,5936-5939,5961-5963,6435-6436,6440-6441,6454-6455,6464-6465,6487-6489,6491-6492,6498-6499,6595-6596

Summary

  • Total: 136 lines
  • Missing: 32 lines
  • Coverage: 76%

mssql_python/pybind/ddbc_bindings.cpp

Lines 4647-4655

  4647 }
  4648 
  4649 static SQLRETURN GetRowData(const SqlHandlePtr& StatementHandle, SQLUSMALLINT colCount,
  4650                             py::list& row, const std::string& charEncoding,
! 4651                             const std::string& wcharEncoding, int charCtype, py::handle messages,
  4652                             const ResultMetadataCache::Snapshot& snapshot,
  4653                             bool completeResult = false, py::handle converters = {},
  4654                             bool batchText = false) {
  4655     PERF_TIMER("SQLGetData_wrap");

Lines 4686-4695

  4686         pending->columns.reserve(colCount);
  4687     }
  4688 
  4689     auto* operation = StatementOperation::current(hStmt);
! 4690     const bool groupScalars =
! 4691         operation && metadata &&
  4692         (!converters || converters.is_none() ||
  4693          (PyDict_CheckExact(converters.ptr()) && PyDict_Size(converters.ptr()) == 0));
  4694     for (SQLSMALLINT i = 1; i <= colCount; ++i) {
  4695         if (groupScalars) {

Lines 5880-5889

  5880     if (indicator != SQL_NULL_DATA &&
  5881         (indicator < 0 || static_cast<size_t>(indicator) > capacity - terminator ||
  5882          (wide && indicator % sizeof(SQLWCHAR))))
  5883         ThrowStdException("Invalid bounded fetch length");
! 5884 }
! 5885 
  5886 void ValidateFetchedRowCount(const ColumnBuffers& buffers, SQLUSMALLINT numCols,
  5887                              SQLULEN numRowsFetched) {
  5888     if (numRowsFetched == 0) {
  5889         ThrowStdException("Driver reported a successful fetch with zero rows");

Lines 5924-5934

  5924     std::vector<ColumnInfoExt> columnInfosExt;
  5925     bool prepared = false;
  5926 };
  5927 
! 5928 // Fetch rows in batches
! 5929 // TODO: Move to anonymous namespace, since it is not used outside this file
! 5930 template <bool strictLengths = false, typename Metadata>
  5931 SQLRETURN ConvertBufferedRows(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& columnNames,
  5932                          py::list& rows, SQLUSMALLINT numCols, SQLULEN& numRowsFetched,
  5933                          const std::vector<SQLUSMALLINT>& lobColumns,
  5934                          const std::string& charEncoding = "utf-16le", int charCtype = SQL_C_WCHAR,

Lines 5932-5943

  5932                          py::list& rows, SQLUSMALLINT numCols, SQLULEN& numRowsFetched,
  5933                          const std::vector<SQLUSMALLINT>& lobColumns,
  5934                          const std::string& charEncoding = "utf-16le", int charCtype = SQL_C_WCHAR,
  5935                          py::handle messages = {}, py::handle converters = {}, SQLULEN firstRow = 0,
! 5936                          int bufferRows = 0, BufferedRowConversion* reusableConversion = nullptr) {
! 5937     BufferedRowConversion localConversion;
! 5938     auto& conversion = reusableConversion ? *reusableConversion : localConversion;
! 5939     auto& columnInfos = conversion.columnInfos;
  5940     auto& columnProcessors = conversion.columnProcessors;
  5941     auto& columnInfosExt = conversion.columnInfosExt;
  5942     if (!conversion.prepared) {
  5943         PERF_TIMER("FetchBatchData::cache_column_metadata");

Lines 5957-5967

  5957             columnInfos[col].processedColumnSize = columnInfos[col].columnSize;
  5958             HandleZeroColumnSizeAtFetch(columnInfos[col].processedColumnSize);
  5959 
  5960             SQLSMALLINT dt = columnInfos[col].dataType;
! 5961             columnInfos[col].bufferBytes =
! 5962                 strictLengths ? BoundColumnBufferBytes(dt, columnInfos[col].columnSize, charCtype)
! 5963                               : 0;
  5964             if (dt == SQL_CHAR || dt == SQL_VARCHAR || dt == SQL_LONGVARCHAR ||
  5965                 dt == SQL_WCHAR || dt == SQL_WVARCHAR || dt == SQL_WLONGVARCHAR) {
  5966                 const bool wide = useWideChar ||
  5967                     dt == SQL_WCHAR || dt == SQL_WVARCHAR || dt == SQL_WLONGVARCHAR;

Lines 6431-6445

  6431 // Start with a small rowset, then use normal batching after the first complete batch.
  6432 // Full-width bindings preserve values without SQLGetData recovery or cursor changes.
  6433 static SQLRETURN FetchReusableTextRows(const SqlHandlePtr& handle, SQLUSMALLINT numCols,
  6434                                        py::list& rows, size_t limit,
! 6435                                        const std::string& charEncoding,
! 6436                                        const std::string& wcharEncoding, int charCtype,
  6437                                        py::handle messages, py::handle converters) {
  6438     PERF_TIMER("FetchReusableTextRows");
  6439     (void)wcharEncoding;
! 6440     if (limit == 0)
! 6441         return SQL_SUCCESS;
  6442     const auto metadata = handle->resultMetadata.snapshot().metadata;
  6443     if (!metadata || metadata->columns.size() != numCols)
  6444         ThrowStdException("Column metadata count does not match result column count");
  6445     const auto& columns = metadata->columns;

Lines 6450-6459

  6450     const size_t maximumBatchRows =
  6451         std::clamp<size_t>(maximumBudget / boundBytes, 1, maximumRows);
  6452     const size_t initialBatchRows =
  6453         std::clamp<size_t>(initialBudget / boundBytes, 1, maximumBatchRows);
! 6454     size_t boundRows = std::min({limit, size_t{100}, initialBatchRows});
! 6455     FetchStateGuard guard(handle, messages, numCols, static_cast<int>(boundRows));
  6456     SQLHSTMT statement = handle->get();
  6457     size_t reservedBytes = 0;
  6458     ReserveNativeFetchBytes(reservedBytes, numCols, boundRows * sizeof(SQLLEN));
  6459     SQLRETURN ret = SQLBindColums(statement, guard.storage->columns, columns, numCols,

Lines 6460-6469

  6460                                   static_cast<int>(boundRows), reservedBytes, charCtype, messages);
  6461     guard.observe(ret);
  6462     guard.configure(boundRows);
  6463     size_t configuredRows = boundRows;
! 6464     // Strides and conversion settings stay fixed across complete-cell rebindings.
! 6465     // Keep this plan local to the call; it owns no pointers into bound storage.
  6466     BufferedRowConversion conversion;
  6467     for (size_t count = 0; count < limit;) {
  6468         const size_t rowArray = std::min(boundRows, limit - count);
  6469         if (rowArray != configuredRows) {

Lines 6483-6496

  6483         if (count < limit && fetched == rowArray && boundRows < maximumBatchRows) {
  6484             const size_t batchRows = std::min(limit - count, maximumBatchRows);
  6485             if (batchRows <= boundRows)
  6486                 continue;
! 6487             guard.observe(SQLFreeStmt_ptr(statement, SQL_UNBIND));
! 6488             guard.storage->columns = ColumnBuffers(numCols, static_cast<int>(batchRows));
! 6489             reservedBytes = 0;
  6490             ReserveNativeFetchBytes(reservedBytes, numCols, batchRows * sizeof(SQLLEN));
! 6491             ret = SQLBindColums(statement, guard.storage->columns, columns, numCols,
! 6492                                 static_cast<int>(batchRows), reservedBytes, charCtype, messages);
  6493             guard.observe(ret);
  6494             boundRows = batchRows;
  6495         }
  6496     }

Lines 6494-6503

  6494             boundRows = batchRows;
  6495         }
  6496     }
  6497     guard.close();
! 6498     return SQL_SUCCESS;
! 6499 }
  6500 SQLRETURN DrainPendingArrowRows(SqlHandlePtr handle, py::list& rows, SQLULEN limit,
  6501                                  const std::string& charEncoding, py::handle messages,
  6502                                  py::handle converters);

Lines 6591-6600

  6591                        column.columnSize > 256);
  6592     }
  6593 
  6594     if (dynamicText && lobColumns.empty()) {
! 6595         // Preserve the caller-size limit before selecting smaller reusable batches.
! 6596         size_t requestedBytes = 0;
  6597         ReserveNativeFetchBytes(requestedBytes, static_cast<size_t>(fetchSize),
  6598                                 BoundRowBufferBytes(columnNames, numCols, charCtype));
  6599         return FetchReusableTextRows(StatementHandle, numCols, rows, fetchSize, charEncoding,
  6600                                      wcharEncoding, charCtype, messages, converters);


📋 Files Needing Attention

📉 Files with overall lowest coverage (click to expand)
mssql_python.pybind.performance_counter.hpp: 0.7%
mssql_python.pybind.logger_bridge.cpp: 57.9%
mssql_python.pybind.vector_support.hpp: 59.5%
mssql_python.pybind.ddbc_bindings.h: 75.4%
mssql_python._native_fetch.py: 80.1%
mssql_python.pybind.row_mapping_cache.hpp: 81.5%
mssql_python.pybind.connection.connection_pool.cpp: 82.5%
mssql_python.pybind.ddbc_bindings.cpp: 84.1%
mssql_python.pybind.connection.connection.cpp: 84.9%
mssql_python.logging.py: 86.8%

🔗 Quick Links

⚙️ Build Summary 📋 Coverage Details

View Azure DevOps Build

Browse Full Coverage Report

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>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 06:15
@jahnvi480 Jahnvi Thakkar (jahnvi480) changed the title PERF: prototype reusable bounded-text fetch buffers PERF: reuse smaller bounded-text rowsets Nov 27, 2026
@jahnvi480
Jahnvi Thakkar (jahnvi480) marked this pull request as ready for review November 27, 2026 06:18

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The Linux/macOS narrow-buffer case cannot meet the density threshold required by the new test assertions, causing the cross-platform contract test to fail.

3 open issues
What changed in this PR

This draft experiment addresses #455 by reducing temporary memory use during bounded-text fetching in the native ODBC layer. It reuses smaller rowsets while retaining full-width native cell buffers.

Changes:

  • Routes eligible fetchall() and fetchmany() results through 1 MiB rowsets, with growth toward 8 MiB for dense values.
  • Adds bound-length and row-count validation while preserving cancellation, cleanup, and existing LOB routing.
  • Expands regression coverage and documents buffer budgets and experimental limitations.

Review validation was limited to source inspection and self-contained sizing calculations; no native build or live-database tests were run.

File Description
tests/​test_query_cancellation.py Extends cancellation coverage to bounded-text rowset fetching.
tests/​test_017_fetch_buffer_sizing.py Adds rowset sizing, driver-call, and invalid-result checks.
tests/​test_017_fetch_bounded_text.py Tests density transitions, mixed types, Unicode boundaries, and converters.
README.md Documents the experimental fetch strategy and memory budgets.
mssql_python/​pybind/​ddbc_bindings.cpp Implements reusable bounded-text rowsets, adaptive growth, and validation.

Review effort: Balanced

Comment thread tests/test_017_fetch_buffer_sizing.py Resolved
Comment thread mssql_python/pybind/ddbc_bindings.cpp Resolved
Comment thread mssql_python/pybind/ddbc_bindings.cpp Resolved
…ches

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>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 06:56

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The new buffer-replacement path lacks failure-injection coverage proving storage survives partial-rebind and cleanup failures, and the README misstates how native buffer memory is reduced.

No open issues 🎉

2 previously missed issues

In code that hasn't changed since last review

Medium severity Add lifetime-failure tests for compact buffer replacement

mssql_python/​pybind/​ddbc_bindings.cpp:5718

The lifetime-failure tests do not reach this new buffer-replacement path. Every _RETAINED_CASES scenario in test_017_fetch_buffer_sizing.py uses VARCHAR(32), while none of the new compact cases injects an unbind or partial-rebind cleanup failure. Add eligible wide-text variants that force growth, fail a partial rebind and its cleanup, and assert that the replacement storage remains alive until successful statement/connection cleanup. Otherwise the existing retention assertions cannot catch lifetime regressions in this path.

Low severity Clarify that buffers still allocate full declared-width cells

README.md:495

The native buffers still allocate each bound cell at its full declared width: SQLBindColums sizes them as fetchSize * BoundColumnBufferBytes(...). The memory reduction comes from binding fewer rows and reusing that smaller rowset, not from eliminating declared-width cell allocations. Please state that distinction so readers do not mistake this for actual-length native buffer allocation.

3 resolved since last review

Review effort: Balanced

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>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 09:26

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed for an unpublished concern about whether the documentation distinguishes buffer reuse and fewer bound rows from full-width native allocations.

No open issues 🎉

Review effort: Balanced

Preserve native buffer and indicator validation, checked allocation budgets, and pending Arrow-row handling alongside reusable text rowsets. Align the invalid native fetch-size regression with main.

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The README needs clarification because memory savings come from binding fewer rows simultaneously, not from avoiding declared-width cell buffers.

1 open issue

Review effort: Balanced

Comment thread README.md Resolved
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings December 1, 2026 05:52
@jahnvi480 Jahnvi Thakkar (jahnvi480) changed the title PERF: reuse smaller bounded-text rowsets PERF: reduce bounded-text rowset memory Dec 1, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because the unconditionally invoked normalizer can crash on valid older LCOV function records, breaking unified coverage generation in some environments.

No open issues 🎉

Review effort: Balanced

Comment thread mssql_python/pybind/ddbc_bindings.cpp Outdated
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<size_t>(bindingBudget / boundBytes, 1, maximumRows));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we check boundBytes is zero or not?
It may cause division by zero crash here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

boundBytes cannot be zero on this path. Both callers select FetchReusableTextRows only when the result contains an eligible bounded-text column, so there is at least one column. BoundRowBufferBytes adds each column's checked buffer capacity plus sizeof(SQLLEN) for its indicator; even a zero-capacity cell would therefore contribute a positive amount. Overflow raises rather than wrapping. The metadata count is also checked before calculating the size. No additional zero guard is needed for the current callers.

Comment thread mssql_python/pybind/ddbc_bindings.cpp Outdated
static_cast<size_t>(guard.storage->columns.indicators[column][row]);
count += fetched;
if (!dense && count < limit && fetched == rowArray) {
dense = bytes / fetched >= boundBytes / 2;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible "fetched" is zero here and cause a zero division crash?
Apparently guard.storage->rowsFetched returning zero row may cause this issue?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The driver can report zero, but it cannot reach this division. This loop calls FetchBatchData<true>, which resets the fetched count before the driver call and rejects a successful fetch when numRowsFetched == 0 (or exceeds the configured rowset), raising Invalid bounded fetch row count before conversion and before returning here. SQL_NO_DATA breaks the loop before this point, and errors also do not reach the division.

The existing compact-zero-rows case in tests/test_017_fetch_buffer_sizing.py injects a successful driver response with a zero fetched count and asserts that exception. No additional check is needed here.

ret = SQLBindColums(statement, guard.storage->columns, columns, numCols,
static_cast<int>(batchRows), reservedBytes, charCtype, messages);
guard.observe(ret);
boundRows = batchRows;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Blocking]: boundRows is getting modified here by batchRows but configuredRows holds old boundRows value. Hence shall we also correct the configuredRows here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

configuredRows intentionally keeps the currently installed SQL_ATTR_ROW_ARRAY_SIZE; boundRows is the capacity of the newly allocated buffers. SQLBindColums does not update the statement's row-array size. At the top of the next iteration, rowArray = min(boundRows, limit - count) differs from configuredRows, so guard.setRowArraySize(rowArray) updates the driver before the next fetch, and only then is configuredRows updated.

Assigning configuredRows = batchRows here without setting the driver attribute would incorrectly skip that required update. The existing growth contract tests check the observed driver rowset sizes and the unbind-before-rebind ordering. No code change is needed.

guard.storage->columns = ColumnBuffers(numCols, static_cast<int>(batchRows));
reservedBytes = 0;
ReserveNativeFetchBytes(reservedBytes, numCols, batchRows * sizeof(SQLLEN));
ret = SQLBindColums(statement, guard.storage->columns, columns, numCols,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we handle any exception here for method SQLBindColums?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An additional local catch is not needed here. SQLBindColums already raises on a failed column binding (Failed to bind column ...), and the FetchStateGuard is constructed before binding. If binding or allocation throws, stack unwinding runs the guard's destructor to reset the row-array size, clear the fetched-count pointer and unbind columns. Cleanup failures are reported without replacing the original exception, and native storage is retained if cleanup cannot safely release driver references. The exception then propagates to Python rather than continuing with a partial binding.

The existing compact-dense-rebind-failure test injects a failure during this growth rebind; partial-binding and persistent-cleanup-failure cases also exercise recovery and storage lifetime. No code change is needed.

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>
Copilot AI balanced review requested due to automatic review settings December 1, 2026 07:42

{
// Fetch rows in batches
// TODO: Move to anonymous namespace, since it is not used outside this file

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human review is needed to assess the performance impact of redundant density scans when rowset growth is already capped.

No open issues 🎉

Review effort: Balanced

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>
Copilot AI balanced review requested due to automatic review settings December 1, 2026 08:36

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The PR description and review clarification overstate sustained memory savings and need to accurately describe density-independent batch growth, startup/short-result savings, and conversion metadata prepared once per native call.

1 open issue

Review effort: Balanced

Comment on lines +6483 to +6484
if (count < limit && fetched == rowArray && boundRows < maximumBatchRows) {
const size_t batchRows = std::min(limit - count, maximumBatchRows);
Copilot AI balanced review requested due to automatic review settings December 2, 2026 01:25

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The PR description misstates the implemented unconditional buffer-growth policy, incorrectly promising sparse-data memory limits and density-based growth, and must be updated.

1 open issue

Review effort: Balanced

@jahnvi480
Jahnvi Thakkar (jahnvi480) marked this pull request as draft December 2, 2026 05:09
auto-merge was automatically disabled December 2, 2026 05:09

Pull request was converted to draft

@jahnvi480
Jahnvi Thakkar (jahnvi480) marked this pull request as ready for review December 2, 2026 05:10
Copilot AI balanced review requested due to automatic review settings December 2, 2026 05:10

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The PR description promises sparse-result memory savings, but the implementation grows after any full batch regardless of payload density, misrepresenting the memory/call tradeoff.

1 open issue

Review effort: Balanced

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-size: large Substantial code update

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants