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

✅ No regression detected

No consistent slowdowns detected across all 2 environments.

0 IMPROVEMENTS 0 SLOWDOWNS 2/2 ENVIRONMENTS

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

Performance diagnostics

Phase times are inclusive diagnostics and must not be added together. They identify where measured time changed, not why it changed.

Unix / SQL Server 2022

5,000 x 8 VARCHAR(8000) / ASCII to UTF-16: ddbc::SQLBindColums +0.586 ms; py::fetchall::row_wrap +0.006 ms; ddbc::SQLDescribeCol_wrap +0.000 ms. Call changes: ddbc::FetchBatchData (78 -> 79 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 79 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 1 calls).
5,000 x 8 VARCHAR(8000) / CP1252 to UTF-16: ddbc::SQLBindColums +0.071 ms; py::fetchall::row_wrap +0.012 ms; ddbc::SQLDescribeCol_wrap +0.000 ms. Call changes: ddbc::FetchBatchData (78 -> 79 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 79 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 1 calls).
5,000 x 8 VARCHAR(8000) / UTF-8 to UTF-16 (astral): ddbc::SQLBindColums +0.054 ms; py::fetchall::row_wrap +0.044 ms; ddbc::SQLDescribeCol::driver_call +0.000 ms. Call changes: ddbc::FetchBatchData (78 -> 79 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 79 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 1 calls).
5,000 x 8 NVARCHAR(4000) / UTF-16 (astral): ddbc::FetchBatchData::SQLFetchScroll_call +2.910 ms; py::fetchall::cpp_call +2.497 ms; ddbc::FetchBatchData +2.281 ms. Call changes: ddbc::FetchBatchData (40 -> 41 calls); ddbc::FetchBatchData::SQLFetchScroll_call (40 -> 41 calls); ddbc::FetchBatchData::cache_column_metadata (39 -> 1 calls).
5,000 x 8 VARCHAR(8000) / short ASCII: ddbc::SQLBindColums +0.044 ms; py::fetchall::row_wrap +0.035 ms. Call changes: ddbc::FetchBatchData (78 -> 79 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 79 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 1 calls).
200 x 8 VARCHAR(8000) / full-width ASCII: ddbc::FetchBatchData::SQLFetchScroll_call +0.490 ms; py::fetchall::cpp_call +0.172 ms; ddbc::FetchAll_wrap +0.172 ms. Call changes: ddbc::FetchBatchData::cache_column_metadata (4 -> 1 calls); ddbc::FetchReusableTextRows (added, removed, or intermittent); ddbc::SQLBindColums (1 -> 2 calls).
5,000 x 8 VARCHAR(8000) / short CP1252: ddbc::FetchBatchData::SQLFetchScroll_call +0.164 ms; ddbc::SQLBindColums +0.038 ms; ddbc::SQLDescribeCol_wrap +0.001 ms. Call changes: ddbc::FetchBatchData (78 -> 79 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 79 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 1 calls).
200 x 8 VARCHAR(8000) / full-width CP1252: ddbc::SQLBindColums +0.061 ms; ddbc::SQLDescribeCol_wrap +0.001 ms; py::fetchall::row_wrap +0.001 ms. Call changes: ddbc::FetchBatchData::cache_column_metadata (4 -> 1 calls); ddbc::FetchReusableTextRows (added, removed, or intermittent); ddbc::SQLBindColums (1 -> 2 calls).
5,000 x 8 VARCHAR(8000) / short UTF-8 (astral): ddbc::SQLBindColums +0.072 ms. Call changes: ddbc::FetchBatchData (78 -> 79 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 79 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 1 calls).
200 x 8 VARCHAR(8000) / full-width UTF-8 (astral): ddbc::SQLBindColums +0.058 ms; py::fetchall::row_wrap +0.001 ms; ddbc::SQLDescribeCol_wrap +0.000 ms. Call changes: ddbc::FetchBatchData::cache_column_metadata (4 -> 1 calls); ddbc::FetchReusableTextRows (added, removed, or intermittent); ddbc::SQLBindColums (1 -> 2 calls).
5,000 x 8 NVARCHAR(4000) / short UTF-16 (astral): no measured phase delta. Call changes: ddbc::FetchBatchData (40 -> 41 calls); ddbc::FetchBatchData::SQLFetchScroll_call (40 -> 41 calls); ddbc::FetchBatchData::cache_column_metadata (39 -> 1 calls).
200 x 8 NVARCHAR(4000) / full-width UTF-16 (astral): ddbc::FetchBatchData +7.590 ms; py::fetchall::cpp_call +7.466 ms; ddbc::FetchAll_wrap +7.448 ms. Call changes: ddbc::FetchBatchData (3 -> 4 calls); ddbc::FetchBatchData::SQLFetchScroll_call (3 -> 4 calls); ddbc::FetchBatchData::cache_column_metadata (2 -> 1 calls).

Unix / SQL Server 2025

5,000 x 8 VARCHAR(8000) / ASCII to UTF-16: ddbc::SQLBindColums +0.520 ms; py::fetchall::cpp_call +0.444 ms; ddbc::FetchBatchData::construct_rows +0.210 ms. Call changes: ddbc::FetchBatchData (78 -> 79 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 79 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 1 calls).
5,000 x 8 VARCHAR(8000) / CP1252 to UTF-16: ddbc::FetchBatchData::SQLFetchScroll_call +1.144 ms; ddbc::SQLBindColums +0.048 ms; py::fetchall::row_wrap +0.012 ms. Call changes: ddbc::FetchBatchData (78 -> 79 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 79 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 1 calls).
5,000 x 8 VARCHAR(8000) / UTF-8 to UTF-16 (astral): ddbc::SQLBindColums +0.074 ms; ddbc::SQLDescribeCol::driver_call +0.000 ms; ddbc::SQLNumResultCols_wrap +0.000 ms. Call changes: ddbc::FetchBatchData (78 -> 79 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 79 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 1 calls).
5,000 x 8 NVARCHAR(4000) / UTF-16 (astral): py::fetchall::row_wrap +0.017 ms. Call changes: ddbc::FetchBatchData (40 -> 41 calls); ddbc::FetchBatchData::SQLFetchScroll_call (40 -> 41 calls); ddbc::FetchBatchData::cache_column_metadata (39 -> 1 calls).
5,000 x 8 VARCHAR(8000) / short ASCII: ddbc::FetchBatchData::SQLFetchScroll_call +0.298 ms; ddbc::FetchBatchData +0.178 ms; ddbc::FetchAll_wrap +0.166 ms. Call changes: ddbc::FetchBatchData (78 -> 79 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 79 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 1 calls).
200 x 8 VARCHAR(8000) / full-width ASCII: ddbc::FetchBatchData::construct_rows +0.228 ms; ddbc::SQLBindColums +0.091 ms; py::fetchall::row_wrap +0.000 ms. Call changes: ddbc::FetchBatchData::cache_column_metadata (4 -> 1 calls); ddbc::FetchReusableTextRows (added, removed, or intermittent); ddbc::SQLBindColums (1 -> 2 calls).
5,000 x 8 VARCHAR(8000) / short CP1252: ddbc::SQLBindColums +0.078 ms; py::fetchall::cpp_call +0.002 ms; py::fetchall::row_wrap +0.001 ms. Call changes: ddbc::FetchBatchData (78 -> 79 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 79 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 1 calls).
200 x 8 VARCHAR(8000) / full-width CP1252: ddbc::FetchAll_wrap +0.724 ms; py::fetchall::cpp_call +0.723 ms; ddbc::FetchBatchData +0.632 ms. Call changes: ddbc::FetchBatchData::cache_column_metadata (4 -> 1 calls); ddbc::FetchReusableTextRows (added, removed, or intermittent); ddbc::SQLBindColums (1 -> 2 calls).

4 additional diagnostic rows are available in the raw ADO artifacts.

All database tasks and timings

Unix / SQL Server 2022

Database task Before After Paired change Result
Connection opening 10.170 ms 9.905 ms -1.8% no signal
SELECT queries 1.268 ms 1.241 ms -1.3% no signal
Row insertion 31.235 ms 31.059 ms -0.5% no signal
Executemany inserts 155.325 ms 156.352 ms +0.6% no signal
Fetch-all queries 121.133 ms 120.901 ms -0.2% no signal
Row-by-row fetching 6.130 ms 6.167 ms +0.3% no signal
Batched row fetching 117.925 ms 118.324 ms +1.1% no signal
Transaction commit and rollback 106.373 ms 105.429 ms -0.9% no signal
Arrow row fetching 109.607 ms 99.644 ms -8.8% no signal
100,000-row insertion 361.033 ms 360.860 ms -1.3% no signal
Row fetching in batches of 100 124.609 ms 125.619 ms +0.1% no signal
Row fetching in batches of 10,000 122.798 ms 126.794 ms +3.3% no signal
Repeated positional queries 33.093 ms 33.176 ms -0.3% no signal
Repeated named-parameter queries 33.509 ms 33.564 ms -0.5% no signal
Legacy 100,000-row insertion 274.607 ms 292.668 ms +8.7% no signal
Insertion with explicit input sizes 532.906 ms 520.682 ms -3.4% no signal
Joined aggregation queries 177.683 ms 177.840 ms -0.0% no signal
Large joined-result fetching 186.484 ms 189.794 ms +1.8% no signal
1.2-million-row fetching 3566.687 ms 3570.085 ms +0.2% no signal
Common table expression queries 5.588 ms 5.357 ms -4.7% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.327 ms 1.319 ms -5.2% no signal
10,000 scalar values / fetchval() (debug disabled) 19.746 ms 19.787 ms -0.2% no signal
10,000 output-converted rows / fetchall() 19.586 ms 19.164 ms -1.0% no signal
10,000 output-converted rows / fetchmany(1000) 23.076 ms 23.374 ms +1.3% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 28.045 ms 28.270 ms +0.6% no signal
5,000 x 8 VARCHAR(8000) / ASCII to UTF-16 38.646 ms 38.391 ms +3.6% no signal
5,000 x 8 VARCHAR(8000) / CP1252 to UTF-16 53.348 ms 52.523 ms -1.5% no signal
5,000 x 8 VARCHAR(8000) / UTF-8 to UTF-16 (astral) 99.596 ms 97.324 ms -2.3% no signal
5,000 x 8 NVARCHAR(4000) / UTF-16 (astral) 89.313 ms 91.853 ms +4.0% no signal
5,000 x 8 VARCHAR(8000) / short ASCII 10.209 ms 10.066 ms -1.0% no signal
200 x 8 VARCHAR(8000) / full-width ASCII 44.157 ms 44.306 ms -1.9% no signal
5,000 x 8 VARCHAR(8000) / short CP1252 13.075 ms 12.672 ms -3.9% no signal
200 x 8 VARCHAR(8000) / full-width CP1252 43.179 ms 42.704 ms -5.5% no signal
5,000 x 8 VARCHAR(8000) / short UTF-8 (astral) 16.438 ms 15.942 ms -0.5% no signal
200 x 8 VARCHAR(8000) / full-width UTF-8 (astral) 51.541 ms 47.136 ms -17.0% no signal
5,000 x 8 NVARCHAR(4000) / short UTF-16 (astral) 14.112 ms 13.955 ms -2.2% no signal
200 x 8 NVARCHAR(4000) / full-width UTF-16 (astral) 59.391 ms 66.836 ms +12.2% no signal
200,000 x 8 VARCHAR(32) / fetchall control 520.027 ms 523.435 ms -0.2% no signal
200,000 x 8 INT / fetchall control 278.267 ms 277.511 ms -0.6% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 30.860 ms 30.684 ms -0.3% no signal

Unix / SQL Server 2025

Database task Before After Paired change Result
Connection opening 82.127 ms 81.527 ms -0.2% no signal
SELECT queries 1.326 ms 1.307 ms -1.8% no signal
Row insertion 32.500 ms 32.828 ms +1.5% no signal
Executemany inserts 156.174 ms 155.592 ms +0.6% no signal
Fetch-all queries 130.071 ms 124.055 ms +0.9% no signal
Row-by-row fetching 6.122 ms 6.221 ms +0.9% no signal
Batched row fetching 122.608 ms 120.419 ms -1.8% no signal
Transaction commit and rollback 110.634 ms 110.232 ms -0.2% no signal
Arrow row fetching 102.635 ms 99.964 ms -4.3% no signal
100,000-row insertion 362.991 ms 374.198 ms -0.2% no signal
Row fetching in batches of 100 132.156 ms 130.527 ms +1.5% no signal
Row fetching in batches of 10,000 133.462 ms 135.060 ms +3.6% no signal
Repeated positional queries 33.946 ms 34.951 ms -0.0% no signal
Repeated named-parameter queries 34.149 ms 34.997 ms +3.9% no signal
Legacy 100,000-row insertion 274.497 ms 274.026 ms -0.2% no signal
Insertion with explicit input sizes 537.971 ms 557.598 ms +1.0% no signal
Joined aggregation queries 169.119 ms 172.624 ms +0.6% no signal
Large joined-result fetching 193.389 ms 192.922 ms +0.1% no signal
1.2-million-row fetching 3605.047 ms 3627.056 ms +0.7% no signal
Common table expression queries 5.225 ms 5.390 ms +3.2% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.726 ms 1.303 ms -24.2% no signal
10,000 scalar values / fetchval() (debug disabled) 19.651 ms 20.415 ms +5.1% no signal
10,000 output-converted rows / fetchall() 20.075 ms 19.840 ms -1.7% no signal
10,000 output-converted rows / fetchmany(1000) 23.758 ms 24.512 ms +3.1% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 28.234 ms 28.608 ms +2.8% no signal
5,000 x 8 VARCHAR(8000) / ASCII to UTF-16 50.677 ms 51.033 ms +1.0% no signal
5,000 x 8 VARCHAR(8000) / CP1252 to UTF-16 61.265 ms 61.158 ms -0.7% no signal
5,000 x 8 VARCHAR(8000) / UTF-8 to UTF-16 (astral) 119.977 ms 108.677 ms -7.7% no signal
5,000 x 8 NVARCHAR(4000) / UTF-16 (astral) 126.570 ms 123.198 ms -4.6% no signal
5,000 x 8 VARCHAR(8000) / short ASCII 10.739 ms 10.635 ms +1.6% no signal
200 x 8 VARCHAR(8000) / full-width ASCII 52.221 ms 50.818 ms -2.0% no signal
5,000 x 8 VARCHAR(8000) / short CP1252 13.211 ms 13.189 ms -1.2% no signal
200 x 8 VARCHAR(8000) / full-width CP1252 50.013 ms 50.758 ms +1.5% no signal
5,000 x 8 VARCHAR(8000) / short UTF-8 (astral) 16.345 ms 16.160 ms -1.9% no signal
200 x 8 VARCHAR(8000) / full-width UTF-8 (astral) 52.941 ms 52.687 ms +0.3% no signal
5,000 x 8 NVARCHAR(4000) / short UTF-16 (astral) 14.440 ms 14.346 ms -1.5% no signal
200 x 8 NVARCHAR(4000) / full-width UTF-16 (astral) 83.010 ms 77.151 ms -9.2% no signal
200,000 x 8 VARCHAR(32) / fetchall control 529.786 ms 513.192 ms -4.1% no signal
200,000 x 8 INT / fetchall control 280.697 ms 276.122 ms -0.1% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 30.732 ms 31.365 ms +0.4% no signal
Build and measurement details

ADO build 196329

PR head: 5790f79be6bbc92fd7c00174755c6d2cc0318dd1
Base: 504c447b16ccbd36dee3fffa0b620e949f2c4d1d
Measured merge: 71499e8edc02a530da50a0c21f70fb90a4795765

  • Unix / SQL Server 2022: Python 3.12.3, x86_64, SQL 16.0.4325.4; 5 paired comparisons and 1 warmup.
  • Unix / SQL Server 2025: Python 3.12.3, x86_64, SQL 17.0.5065.9; 5 paired comparisons and 1 warmup.

A consistent change requires more than 20% median paired movement, at least 1 ms between the median runtimes, and at least 80% of pairs exceeding the relative threshold in the same direction. A slowdown without enough pair agreement is reported as inconsistent.

The displayed change is the median of paired before-and-after ratios. It is not recalculated from the two displayed median runtimes.

Both revisions use profiling-enabled builds on the same agent and database, with alternating order and discarded warmups. Results are diagnostic and do not represent production-wheel latency.

Raw samples and logs are attached to the ADO run as profiler-* artifacts.

@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: 15262 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 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 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

5 participants