Skip to content

PERF: reuse smaller bounded-text rowsets - #920

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

Jahnvi Thakkar (jahnvi480) wants to merge 14 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

Replace the slow per-cell text-reading prototype with smaller, complete, reusable bound rowsets. This reduces declared-width temporary storage without requiring unsupported multirow SQLGetData recovery.

  • For fetchall()/fetchmany() results containing 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 at most 1,000 subsequently. Always retain at least one complete row, including rows exceeding the budget.
  • Decode directly into actual-length Python results using the existing bound-column processors. Remove the old starter-buffer, length-probe and text-continuation machinery; there is no additional compact native copy.
  • If observed payload occupies at least half the declared row width, safely unbind and adapt to the ordinary 8 MiB rowset budget. Full-width values arriving after short samples remain complete.
  • Share checked row-byte accounting, retain heap-owned binding lifetimes through cleanup failures, validate row counts before indexing, and reject invalid/truncated lengths before conversion. Compile the additional length checks out of unchanged fetch paths.
  • Preserve cancellation fences, diagnostics, converter ownership, Unicode/astral and CP1252 fidelity, embedded NULs, NULL/empty values, interleaved fetches, existing LOB routing and the forward-only cursor type.

Status: ready for review at the user's request. Correctness validation passes locally, and the old per-cell-call bottleneck has been removed. Repeated generated-query and materialized-table comparisons do not consistently demonstrate improved large-result throughput. The 256-character eligibility threshold and 1 MiB tradeoff remain experimental; this is not a universal speedup claim.

The branch contains main snapshot cfd8b9e69699e5e44d7c1d62115dd8b706ac7985; the replacement is committed as 2068695b0f268485836fe8e3cd672810719b1060. The PR targets main. Only the five optimization/documentation/test files differ from the pinned base; benchmark artifacts and native binaries are not committed.

Driver calls and storage: On the verified 5,000-row workload (integer ID plus eight short VARCHAR(8000) payload columns), the old prototype made 5,001 SQLFetch plus 45,000 SQLGetData calls. The replacement makes 626 SQLFetchScroll, zero SQLFetch, and zero SQLGetData calls. Pinned main makes 78 SQLFetchScroll calls. These are fetch/read driver-call counts, not network round trips. The replacement's eight-row reusable binding is approximately 0.98 MiB of data plus indicators versus main's 65-row binding at approximately 7.94 MiB. Python results, allocator capacities and metadata are outside those buffer targets.

Review/CI follow-up (09c272d4c246faf5d420e1dd676d4525c8095941): Fixed the Linux/macOS narrow-text contract: UTF-8 expansion reserves 256,084 bytes per row, but the full payload is only 128,004 bytes, below the half-width density cutoff. The test now expects the supported four-row sparse binding rather than a 32-row dense rebind. All inspected failing Linux test jobs and the unified-coverage job failed on this same assertion. Growth now requires a completely filled rowset, avoiding a large allocation solely to discover EOF after a small dense result; an isolated one-row full-width regression asserts that no growth rebind occurs.

Fresh validation: cmake --build mssql_python\pybind\build\x64\py313 --config Release passed, followed by .\.venv\Scripts\python.exe -m pytest tests\test_017_fetch_buffer_sizing.py tests\test_017_fetch_bounded_text.py tests\test_query_cancellation.py -q --disable-warnings --tb=short - 275 passed. .\.venv\Scripts\python.exe -m pre_commit run black-check --all-files --hook-stage pre-push and commit/push hooks passed. Windows runtime validation and Unix sizing arithmetic are verified locally; the Linux/macOS runtime rerun is still pending.

A fresh driver-pointer observation on the rebuilt follow-up source confirms 626 SQLFetchScroll calls and no SQLFetch or SQLGetData calls for the same 5,000-row sparse workload. The detailed latency tables below belong to the earlier reusable-rowset commit 2068695b, not the removed unbound prototype or a new performance claim for this follow-up. The existing 45% coverage comment belongs to canceled build 195419 at 7362ec45, which still contained the removed prototype. Build 195430 failed its coverage test run on the narrow assertion and therefore could not publish an updated report. This push fixes that failure; the replacement coverage percentage must come from the new successful CI artifact, not from manually changing the bot's report.

Latest Windows measurements (2026-11-27): Python 3.13.17, matching MSVC Release /O2/NDEBUG, SQL Server 15.0.4382.1 and msodbcsql18 18.06.0002. Both processes loaded the same driver DLL hash. Separate pinned package/native roots, profiling compiled out and test-pointer access ON; no interposition callbacks during latency measurement. Six counterbalanced fresh-process rounds per scenario; execute, GC, verification and cleanup excluded. Every returned value is checked outside timing. Unsampled latency runs exclude the memory-sampling thread.

Workload: eight payload columns plus integer ID Generated query main / replacement median, ms Materialized table main / replacement median, ms
5,000 short values declared VARCHAR(8000) 14.94 / 14.86 15.18 / 13.41
50,000 short values declared VARCHAR(8000) 155.43 / 122.38 124.56 / 130.18
200 full-width VARCHAR(8000) rows 98.43 / 98.33 83.07 / 84.60
Three short, wide-declared rows 2.61 / 0.79 3.15 / 0.81
5,000 VARCHAR(32) control rows 11.00 / 11.96 12.48 / 12.21
5,000 BIGINT control rows 6.77 / 8.60 10.42 / 8.22

The generated 50,000-row ranges were main 120.46?171.90 ms, replacement 108.59?142.52 ms; materialized ranges were main 115.03?154.53 ms, replacement 117.06?292.18 ms. Materialized data was prepared in a connection-local temporary table with a unique clustered index before the measured SELECT. This separates result generation from the fetch workload, but does not remove server/network/shared-host variability. Severe outliers affected both legs and unchanged controls, including full-width observations above 0.6 s on main and 2.7 s on the replacement. All observations are preserved; medians and overlapping ranges are not proof of no regression. The materialized large-result median remains 4.5% slower, so throughput readiness is not established.

A separate six-round 1 ms private-memory-sampling run of the reusable-rowset implementation before compile-time specialization observed median process-private increases of 5.57 ? 3.64 MiB at 5,000 sparse rows and 40.36 ? 38.40 MiB at 50,000 rows. These are advisory whole-process samples, not exact allocation peaks; allocator behavior and retained Python results dominate large outputs, and transient peaks can be missed.

Matching profiling-enabled Release builds separately verified the intended paths: 78 versus 626 native fetch calls for sparse text, and seven fetch calls on both numeric controls. In the numeric attribution observations, most of the elapsed difference was inside driver fetch calls, not metadata processing. These instrumented observations are not shipped-latency measurements. Both builds were subsequently rebuilt and verified with native profiling OFF.

Final validation:

  • cmake --build mssql_python\pybind\build\x64\py313 --config Release ? passed with the active development interpreter and VS 2022 environment; Release/NDEBUG, profiling OFF, test-pointer interposition ON. Matching baseline/profiled/restored builds also passed.
  • .\.venv\Scripts\python.exe -m pytest tests\test_000_dependencies.py tests\test_013_encoding_decoding.py tests\test_017_fetch_buffer_sizing.py tests\test_017_fetch_bounded_text.py tests\test_017_fetchmany_fetchone_interleave.py tests\test_038_fetch_temporal.py tests\test_native_fetch_dispatch.py tests\test_fetch_settings_cache.py tests\test_output_converter_bytes.py tests\test_query_cancellation.py -q --disable-warnings --tb=short ? 1,185 passed, 27 skipped, on the final restored unprofiled build.
  • .\.venv\Scripts\python.exe -m pytest tests\test_017_varchar_cp1252_boundary.py tests\test_json.py -q --disable-warnings --tb=short ? 76 passed, 208 skipped. Native JSON/server/provider capabilities unavailable on the SQL Server 2019 target remain unvalidated.
  • .\.venv\Scripts\python.exe -m pytest tests\test_009_pooling.py -q --disable-warnings --tb=short ? 68 passed, 28 skipped in a separate process, preserving global pool-state isolation.
  • .\.venv\Scripts\python.exe -m pytest tests\test_017_fetch_buffer_sizing.py tests\test_017_fetch_bounded_text.py tests\test_query_cancellation.py -k 'buffer_contract or checked_fetch_buffer or reusable_rowset or grouped_scalar_cancel' -q --disable-warnings --tb=short ? 49 passed, 225 deselected after introducing compile-time specialization.
  • .\.venv\Scripts\python.exe -m pre_commit run black-check --all-files --hook-stage pre-push ? passed; commit and push hooks passed. git diff --cached --check and git diff --check passed; the remote branch and PR head were re-read and match the committed replacement.

An initial combined pool/fetch run produced three connection-isolation failures after global pool limits were changed. A targeted ordered pool/connection-isolation probe also reproduces the same pool size limit reached failure on pinned main (one passed, one failed). The separately isolated final suites above pass; no unrelated pool-test behavior was changed.

Not run: full repository suite, strict source/stub typing harness, Linux/macOS/ARM64 runtime validation, alternative-provider validation, production-load/WAN measurements. Hosted GitHub/ADO checks are separate from local validation and have not been claimed complete for this new head.

Raw per-round observations, binary/source identities and build/test logs remain in the originating session artifacts: reusable-final-comparison.jsonl, reusable-final-performance-report.json, reusable-final-driver-counts.json, reusable-unsampled-comparison.jsonl, reusable-unsampled-report.json, reusable-materialized-comparison.jsonl, reusable-materialized-report.json, reusable-profile-*-*.json, reusable-publication-regressions.log, reusable-publication-pool-regressions.log, and reusable-boundary-json-regressions.log.

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::FetchBatchData +1.655 ms; ddbc::FetchBatchData::SQLFetchScroll_call +1.519 ms; py::fetchall::cpp_call +0.057 ms. Call changes: ddbc::FetchBatchData (78 -> 626 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 626 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 625 calls).
5,000 x 8 VARCHAR(8000) / CP1252 to UTF-16: ddbc::FetchBatchData::SQLFetchScroll_call +2.102 ms; ddbc::FetchBatchData +0.044 ms; ddbc::FetchBatchData::cache_column_metadata +0.041 ms. Call changes: ddbc::FetchBatchData (78 -> 626 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 626 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 625 calls).
5,000 x 8 VARCHAR(8000) / UTF-8 to UTF-16 (astral): ddbc::FetchBatchData +9.400 ms; py::fetchall::cpp_call +9.273 ms; ddbc::FetchAll_wrap +9.171 ms. Call changes: ddbc::FetchBatchData (78 -> 626 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 626 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 625 calls).
5,000 x 8 NVARCHAR(4000) / UTF-16 (astral): ddbc::FetchBatchData::construct_rows +0.629 ms; py::fetchall::row_wrap +0.026 ms; ddbc::FetchBatchData::cache_column_metadata +0.010 ms. Call changes: ddbc::FetchBatchData (40 -> 314 calls); ddbc::FetchBatchData::SQLFetchScroll_call (40 -> 314 calls); ddbc::FetchBatchData::cache_column_metadata (39 -> 313 calls).
5,000 x 8 VARCHAR(8000) / short ASCII: ddbc::FetchBatchData +0.630 ms; ddbc::FetchAll_wrap +0.351 ms; py::fetchall::cpp_call +0.333 ms. Call changes: ddbc::FetchBatchData (78 -> 626 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 626 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 625 calls).
200 x 8 VARCHAR(8000) / full-width ASCII: ddbc::FetchBatchData::SQLFetchScroll_call +1.210 ms; py::fetchall::cpp_call +0.890 ms; ddbc::FetchAll_wrap +0.889 ms. Call changes: ddbc::FetchReusableTextRows (added, removed, or intermittent); ddbc::SQLBindColums (1 -> 2 calls).
5,000 x 8 VARCHAR(8000) / short CP1252: ddbc::FetchBatchData +0.685 ms; ddbc::FetchAll_wrap +0.442 ms; py::fetchall::cpp_call +0.355 ms. Call changes: ddbc::FetchBatchData (78 -> 626 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 626 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 625 calls).
200 x 8 VARCHAR(8000) / full-width CP1252: ddbc::SQLBindColums +0.033 ms; py::fetchall::row_wrap +0.003 ms. Call changes: ddbc::FetchReusableTextRows (added, removed, or intermittent); ddbc::SQLBindColums (1 -> 2 calls).
5,000 x 8 VARCHAR(8000) / short UTF-8 (astral): ddbc::FetchBatchData +0.583 ms; py::fetchall::cpp_call +0.321 ms; ddbc::FetchAll_wrap +0.256 ms. Call changes: ddbc::FetchBatchData (78 -> 626 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 626 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 625 calls).
200 x 8 VARCHAR(8000) / full-width UTF-8 (astral): ddbc::FetchBatchData::construct_rows +0.224 ms; ddbc::SQLBindColums +0.065 ms; py::fetchall::row_wrap +0.001 ms. Call changes: ddbc::FetchReusableTextRows (added, removed, or intermittent); ddbc::SQLBindColums (1 -> 2 calls).
5,000 x 8 NVARCHAR(4000) / short UTF-16 (astral): ddbc::FetchBatchData +0.344 ms; ddbc::FetchBatchData::construct_rows +0.178 ms; ddbc::FetchBatchData::SQLFetchScroll_call +0.069 ms. Call changes: ddbc::FetchBatchData (40 -> 314 calls); ddbc::FetchBatchData::SQLFetchScroll_call (40 -> 314 calls); ddbc::FetchBatchData::cache_column_metadata (39 -> 313 calls).
200 x 8 NVARCHAR(4000) / full-width UTF-16 (astral): ddbc::FetchBatchData +6.298 ms; ddbc::FetchAll_wrap +6.198 ms; py::fetchall::cpp_call +6.197 ms. Call changes: ddbc::FetchBatchData (3 -> 4 calls); ddbc::FetchBatchData::SQLFetchScroll_call (3 -> 4 calls); ddbc::FetchBatchData::cache_column_metadata (2 -> 3 calls).

Unix / SQL Server 2025

5,000 x 8 VARCHAR(8000) / ASCII to UTF-16: ddbc::FetchBatchData::cache_column_metadata +0.022 ms; py::fetchall::row_wrap +0.015 ms. Call changes: ddbc::FetchBatchData (78 -> 626 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 626 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 625 calls).
5,000 x 8 VARCHAR(8000) / CP1252 to UTF-16: py::fetchall::row_wrap +0.015 ms; ddbc::FetchBatchData::cache_column_metadata +0.008 ms. Call changes: ddbc::FetchBatchData (78 -> 626 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 626 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 625 calls).
5,000 x 8 VARCHAR(8000) / UTF-8 to UTF-16 (astral): py::fetchall::row_wrap +0.047 ms; ddbc::SQLDescribeCol_wrap +0.000 ms; ddbc::SQLDescribeCol::driver_call +0.000 ms. Call changes: ddbc::FetchBatchData (78 -> 626 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 626 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 625 calls).
5,000 x 8 NVARCHAR(4000) / UTF-16 (astral): ddbc::FetchBatchData::construct_rows +3.996 ms; ddbc::FetchBatchData::cache_column_metadata +0.032 ms; ddbc::SQLDescribeCol_wrap +0.001 ms. Call changes: ddbc::FetchBatchData (40 -> 314 calls); ddbc::FetchBatchData::SQLFetchScroll_call (40 -> 314 calls); ddbc::FetchBatchData::cache_column_metadata (39 -> 313 calls).
5,000 x 8 VARCHAR(8000) / short ASCII: ddbc::FetchBatchData +0.565 ms; py::fetchall::cpp_call +0.317 ms; ddbc::FetchAll_wrap +0.259 ms. Call changes: ddbc::FetchBatchData (78 -> 626 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 626 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 625 calls).
200 x 8 VARCHAR(8000) / full-width ASCII: ddbc::FetchBatchData::construct_rows +0.139 ms; ddbc::SQLBindColums +0.043 ms; py::fetchall::cpp_call +0.013 ms. Call changes: ddbc::FetchReusableTextRows (added, removed, or intermittent); ddbc::SQLBindColums (1 -> 2 calls).
5,000 x 8 VARCHAR(8000) / short CP1252: ddbc::FetchBatchData +0.959 ms; py::fetchall::cpp_call +0.780 ms; ddbc::FetchAll_wrap +0.623 ms. Call changes: ddbc::FetchBatchData (78 -> 626 calls); ddbc::FetchBatchData::SQLFetchScroll_call (78 -> 626 calls); ddbc::FetchBatchData::cache_column_metadata (77 -> 625 calls).
200 x 8 VARCHAR(8000) / full-width CP1252: ddbc::FetchBatchData::construct_rows +0.126 ms; ddbc::FetchBatchData::SQLFetchScroll_call +0.072 ms; ddbc::SQLBindColums +0.050 ms. Call changes: 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.212 ms 10.081 ms -1.5% no signal
SELECT queries 1.248 ms 1.274 ms +2.5% no signal
Row insertion 32.115 ms 32.040 ms +0.0% no signal
Executemany inserts 158.635 ms 157.325 ms -1.4% no signal
Fetch-all queries 120.750 ms 120.712 ms -0.5% no signal
Row-by-row fetching 6.126 ms 6.079 ms -0.9% no signal
Batched row fetching 117.664 ms 121.798 ms +3.9% no signal
Transaction commit and rollback 109.141 ms 108.915 ms +0.2% no signal
Arrow row fetching 97.844 ms 99.503 ms +1.3% no signal
100,000-row insertion 378.282 ms 362.476 ms -4.4% no signal
Row fetching in batches of 100 124.342 ms 124.075 ms -0.2% no signal
Row fetching in batches of 10,000 126.351 ms 123.608 ms -0.8% no signal
Repeated positional queries 33.919 ms 33.918 ms -0.0% no signal
Repeated named-parameter queries 34.162 ms 34.035 ms -0.4% no signal
Legacy 100,000-row insertion 273.252 ms 276.987 ms +1.4% no signal
Insertion with explicit input sizes 535.746 ms 535.316 ms -1.2% no signal
Joined aggregation queries 184.407 ms 179.707 ms -2.5% no signal
Large joined-result fetching 188.449 ms 197.285 ms +4.7% no signal
1.2-million-row fetching 3535.282 ms 3521.779 ms -0.4% no signal
Common table expression queries 5.472 ms 5.410 ms -0.0% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.302 ms 1.299 ms +1.2% no signal
10,000 scalar values / fetchval() (debug disabled) 19.726 ms 19.539 ms -0.1% no signal
10,000 output-converted rows / fetchall() 20.009 ms 19.774 ms -0.5% no signal
10,000 output-converted rows / fetchmany(1000) 23.810 ms 24.026 ms +0.6% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 28.381 ms 28.452 ms -2.9% no signal
5,000 x 8 VARCHAR(8000) / ASCII to UTF-16 45.302 ms 45.285 ms +4.2% no signal
5,000 x 8 VARCHAR(8000) / CP1252 to UTF-16 56.004 ms 55.893 ms -0.2% no signal
5,000 x 8 VARCHAR(8000) / UTF-8 to UTF-16 (astral) 103.088 ms 112.336 ms +7.5% no signal
5,000 x 8 NVARCHAR(4000) / UTF-16 (astral) 89.710 ms 83.808 ms -6.4% no signal
5,000 x 8 VARCHAR(8000) / short ASCII 10.050 ms 10.394 ms +3.6% no signal
200 x 8 VARCHAR(8000) / full-width ASCII 43.513 ms 44.411 ms +2.1% no signal
5,000 x 8 VARCHAR(8000) / short CP1252 12.712 ms 13.050 ms +2.7% no signal
200 x 8 VARCHAR(8000) / full-width CP1252 44.753 ms 42.549 ms -6.5% no signal
5,000 x 8 VARCHAR(8000) / short UTF-8 (astral) 15.642 ms 15.942 ms +3.5% no signal
200 x 8 VARCHAR(8000) / full-width UTF-8 (astral) 47.839 ms 46.581 ms -2.6% no signal
5,000 x 8 NVARCHAR(4000) / short UTF-16 (astral) 13.835 ms 13.629 ms -1.2% no signal
200 x 8 NVARCHAR(4000) / full-width UTF-16 (astral) 60.669 ms 66.896 ms +4.9% no signal
200,000 x 8 VARCHAR(32) / fetchall control 519.673 ms 534.715 ms +2.2% no signal
200,000 x 8 INT / fetchall control 274.860 ms 274.598 ms +0.4% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 30.937 ms 31.747 ms +1.4% no signal

Unix / SQL Server 2025

Database task Before After Paired change Result
Connection opening 80.903 ms 81.198 ms +0.5% no signal
SELECT queries 1.331 ms 1.307 ms -0.6% no signal
Row insertion 31.913 ms 31.887 ms -0.1% no signal
Executemany inserts 153.679 ms 153.515 ms +0.1% no signal
Fetch-all queries 120.818 ms 121.675 ms +1.0% no signal
Row-by-row fetching 6.018 ms 6.043 ms +0.4% no signal
Batched row fetching 117.928 ms 118.560 ms +0.6% no signal
Transaction commit and rollback 109.314 ms 109.910 ms +0.5% no signal
Arrow row fetching 100.219 ms 98.922 ms -0.6% no signal
100,000-row insertion 376.282 ms 374.779 ms -0.8% no signal
Row fetching in batches of 100 129.403 ms 128.855 ms -0.4% no signal
Row fetching in batches of 10,000 126.081 ms 124.543 ms -2.3% no signal
Repeated positional queries 33.710 ms 33.611 ms -1.3% no signal
Repeated named-parameter queries 34.202 ms 33.774 ms -1.0% no signal
Legacy 100,000-row insertion 272.392 ms 274.611 ms +0.7% no signal
Insertion with explicit input sizes 550.455 ms 551.525 ms +0.9% no signal
Joined aggregation queries 168.478 ms 163.804 ms -2.8% no signal
Large joined-result fetching 194.676 ms 190.767 ms -3.8% no signal
1.2-million-row fetching 3519.183 ms 3562.755 ms +1.6% no signal
Common table expression queries 5.465 ms 5.412 ms -0.5% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.671 ms 1.346 ms +1.4% no signal
10,000 scalar values / fetchval() (debug disabled) 19.550 ms 19.463 ms -0.4% no signal
10,000 output-converted rows / fetchall() 19.461 ms 19.488 ms +1.2% no signal
10,000 output-converted rows / fetchmany(1000) 23.067 ms 24.490 ms +8.3% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 28.099 ms 27.755 ms -0.3% no signal
5,000 x 8 VARCHAR(8000) / ASCII to UTF-16 50.217 ms 45.896 ms -0.5% no signal
5,000 x 8 VARCHAR(8000) / CP1252 to UTF-16 60.234 ms 57.318 ms -3.4% no signal
5,000 x 8 VARCHAR(8000) / UTF-8 to UTF-16 (astral) 118.111 ms 105.320 ms -7.6% no signal
5,000 x 8 NVARCHAR(4000) / UTF-16 (astral) 122.154 ms 115.580 ms -6.7% no signal
5,000 x 8 VARCHAR(8000) / short ASCII 10.046 ms 10.376 ms +2.4% no signal
200 x 8 VARCHAR(8000) / full-width ASCII 50.327 ms 50.401 ms +0.4% no signal
5,000 x 8 VARCHAR(8000) / short CP1252 12.453 ms 13.275 ms +7.2% no signal
200 x 8 VARCHAR(8000) / full-width CP1252 51.690 ms 50.998 ms -1.6% no signal
5,000 x 8 VARCHAR(8000) / short UTF-8 (astral) 24.811 ms 16.518 ms -34.8% no signal
200 x 8 VARCHAR(8000) / full-width UTF-8 (astral) 52.819 ms 53.552 ms +1.4% no signal
5,000 x 8 NVARCHAR(4000) / short UTF-16 (astral) 14.240 ms 14.534 ms +2.6% no signal
200 x 8 NVARCHAR(4000) / full-width UTF-16 (astral) 78.708 ms 75.417 ms -4.2% no signal
200,000 x 8 VARCHAR(32) / fetchall control 514.989 ms 525.048 ms +1.8% no signal
200,000 x 8 INT / fetchall control 267.956 ms 279.119 ms +4.0% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 31.008 ms 30.924 ms +0.8% no signal
Build and measurement details

ADO build 196072

PR head: 16c0fc0acb542e56b0ffaedfaeaf5fa2a83127ac
Base: df875895484e9219753bb5bdce9f62cfb462692b
Measured merge: 7127ed2c3d7425642390cc41b09c900580a7bd7c

  • 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

77%


🎯 Overall Coverage

87%


📈 Total Lines Covered: 15227 out of 17445
📁 Project: mssql-python


Diff Coverage

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

  • mssql_python/pybind/ddbc_bindings.cpp (77.4%): Missing lines 4651,4690-4691,5882-5884,5960-5962,6438-6439,6443-6444,6457-6458,6467-6468,6490-6492,6494-6495,6501-6502,6598-6599

Summary

  • Total: 115 lines
  • Missing: 26 lines
  • Coverage: 77%

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 5878-5888

  5878     const bool decimal = type == SQL_DECIMAL || type == SQL_NUMERIC;
  5879     const size_t terminator = text ? (wide ? sizeof(SQLWCHAR) : 1) : (decimal ? 1 : 0);
  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) {

Lines 5956-5966

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

Lines 6434-6448

  6434     PERF_TIMER("FetchReusableTextRows");
  6435     (void)wcharEncoding;
  6436     if (limit == 0)
  6437         return SQL_SUCCESS;
! 6438     const auto metadata = handle->resultMetadata.snapshot().metadata;
! 6439     if (!metadata || metadata->columns.size() != numCols)
  6440         ThrowStdException("Column metadata count does not match result column count");
  6441     const auto& columns = metadata->columns;
  6442     constexpr size_t maximumRows = 1000;
! 6443     constexpr size_t denseBudget = size_t{8} * 1024 * 1024;
! 6444     constexpr size_t bindingBudget = size_t{1} * 1024 * 1024;
  6445     const size_t boundBytes = BoundRowBufferBytes(columns, numCols, charCtype);
  6446     const size_t sparseRows =
  6447         std::min(limit, std::clamp<size_t>(bindingBudget / boundBytes, 1, maximumRows));
  6448     size_t boundRows = std::min(sparseRows, size_t{100});

Lines 6453-6462

  6453     SQLRETURN ret = SQLBindColums(statement, guard.storage->columns, columns, numCols,
  6454                                   static_cast<int>(boundRows), reservedBytes, charCtype, messages);
  6455     guard.observe(ret);
  6456     guard.configure(boundRows);
! 6457     size_t configuredRows = boundRows;
! 6458     bool dense = false;
  6459     for (size_t count = 0; count < limit;) {
  6460         const size_t rowArray = std::min(boundRows, limit - count);
  6461         if (rowArray != configuredRows) {
  6462             guard.setRowArraySize(rowArray);

Lines 6463-6472

  6463             configuredRows = rowArray;
  6464         }
  6465         ret = FetchBatchData<true>(statement, guard.storage->columns, columns, rows, numCols,
  6466                              guard.storage->rowsFetched, {}, charEncoding, charCtype, messages,
! 6467                              converters, rowArray);
! 6468         CheckFetchError(handle, ret);
  6469         if (ret == SQL_NO_DATA)
  6470             break;
  6471         if (!SQL_SUCCEEDED(ret))
  6472             return ret;

Lines 6486-6499

  6486                 dense ? std::clamp<size_t>(denseBudget / boundBytes, 1, maximumRows) : sparseRows;
  6487             const size_t batchRows = std::min(limit - count, targetRows);
  6488             if (batchRows <= boundRows)
  6489                 continue;
! 6490             guard.observe(SQLFreeStmt_ptr(statement, SQL_UNBIND));
! 6491             guard.storage->columns = ColumnBuffers(numCols, static_cast<int>(batchRows));
! 6492             reservedBytes = 0;
  6493             ReserveNativeFetchBytes(reservedBytes, numCols, batchRows * sizeof(SQLLEN));
! 6494             ret = SQLBindColums(statement, guard.storage->columns, columns, numCols,
! 6495                                 static_cast<int>(batchRows), reservedBytes, charCtype, messages);
  6496             guard.observe(ret);
  6497             boundRows = batchRows;
  6498         }
  6499     }

Lines 6497-6506

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

Lines 6594-6603

  6594                        column.columnSize > 256);
  6595     }
  6596 
  6597     if (dynamicText && lobColumns.empty()) {
! 6598         // Preserve the caller-size limit before selecting smaller reusable batches.
! 6599         size_t requestedBytes = 0;
  6600         ReserveNativeFetchBytes(requestedBytes, static_cast<size_t>(fetchSize),
  6601                                 BoundRowBufferBytes(columnNames, numCols, charCtype));
  6602         return FetchReusableTextRows(StatementHandle, numCols, rows, fetchSize, charEncoding,
  6603                                      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: 83.7%
mssql_python.pybind.connection.connection.cpp: 84.2%
mssql_python.pybind.ddbc_bindings.cpp: 84.2%
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>
Copilot AI balanced review requested due to automatic review settings November 28, 2026 13:32

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

Native ODBC rowset rebinding and cleanup still need cross-platform runtime validation, and throughput evidence for the experimental policy remains inconclusive.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

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

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 bounded-text test can truncate UTF-8 input under the database’s default collation, causing its full-value assertions to fail before retrieval is tested.

No open issues 🎉

Review effort: Balanced

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

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

Native rowset rebinding and cleanup still need cross-platform runtime validation, and inconclusive throughput evidence for the automatically enabled experimental sizing policy requires human review.

No open issues 🎉

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

3 participants