Skip to content

PERF: reuse smaller bounded-text rowsets - #920

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

Jahnvi Thakkar (jahnvi480) wants to merge 10 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 +8.262 ms; ddbc::FetchBatchData::SQLFetchScroll_call +7.498 ms; py::fetchall::cpp_call +5.436 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 +0.440 ms; ddbc::SQLDescribeCol_wrap +0.003 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 VARCHAR(8000) / UTF-8 to UTF-16 (astral): ddbc::FetchBatchData +7.222 ms; ddbc::FetchAll_wrap +7.025 ms; py::fetchall::cpp_call +6.939 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::SQLDescribeCol::driver_call +0.000 ms; ddbc::SQLNumResultCols_wrap +0.000 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.515 ms; ddbc::FetchAll_wrap +0.179 ms; ddbc::FetchBatchData::SQLFetchScroll_call +0.146 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::SQLBindColums +0.052 ms; ddbc::SQLNumResultCols_wrap +0.000 ms; ddbc::SQLDescribeCol::driver_call +0.000 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.515 ms; py::fetchall::cpp_call +0.466 ms; ddbc::FetchAll_wrap +0.293 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.042 ms; ddbc::SQLDescribeCol_wrap +0.000 ms; ddbc::SQLNumResultCols_wrap +0.000 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.338 ms; ddbc::FetchBatchData::SQLFetchScroll_call +0.244 ms; py::fetchall::cpp_call +0.069 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.248 ms; ddbc::SQLBindColums +0.030 ms; ddbc::SQLDescribeCol_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.358 ms; ddbc::FetchBatchData::construct_rows +0.154 ms; ddbc::FetchBatchData::SQLFetchScroll_call +0.011 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::SQLFetchScroll_call +6.063 ms; ddbc::FetchBatchData +4.639 ms; py::fetchall::cpp_call +4.481 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 +3.036 ms; ddbc::FetchBatchData::SQLFetchScroll_call +2.347 ms; ddbc::FetchBatchData::construct_rows +0.022 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 +1.285 ms; ddbc::FetchBatchData +0.715 ms; ddbc::FetchAll_wrap +0.491 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 +2.185 ms; py::fetchall::cpp_call +1.971 ms; ddbc::FetchAll_wrap +1.965 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 +1.103 ms; ddbc::FetchBatchData::cache_column_metadata +0.014 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.534 ms; ddbc::FetchAll_wrap +0.277 ms; py::fetchall::cpp_call +0.269 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.239 ms; ddbc::SQLBindColums +0.063 ms; py::fetchall::row_wrap +0.002 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.930 ms; py::fetchall::cpp_call +0.770 ms; ddbc::FetchAll_wrap +0.740 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.165 ms; ddbc::SQLBindColums +0.082 ms; ddbc::FetchAll_wrap +0.048 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.340 ms 10.729 ms +1.8% no signal
SELECT queries 1.323 ms 1.357 ms +2.6% no signal
Row insertion 31.829 ms 31.811 ms -0.1% no signal
Executemany inserts 159.685 ms 159.013 ms -1.8% no signal
Fetch-all queries 117.706 ms 118.174 ms +1.0% no signal
Row-by-row fetching 5.979 ms 5.880 ms -1.6% no signal
Batched row fetching 116.467 ms 115.572 ms -1.8% no signal
Transaction commit and rollback 108.247 ms 108.763 ms +1.0% no signal
Arrow row fetching 87.934 ms 93.101 ms +6.1% no signal
100,000-row insertion 370.100 ms 358.443 ms +0.6% no signal
Row fetching in batches of 100 124.020 ms 123.977 ms +0.5% no signal
Row fetching in batches of 10,000 122.740 ms 126.755 ms +1.7% no signal
Repeated positional queries 33.847 ms 33.755 ms -0.3% no signal
Repeated named-parameter queries 33.949 ms 33.890 ms -0.2% no signal
Legacy 100,000-row insertion 270.798 ms 274.266 ms +1.2% no signal
Insertion with explicit input sizes 428.332 ms 419.061 ms +0.1% no signal
Joined aggregation queries 182.367 ms 180.789 ms -0.9% no signal
Large joined-result fetching 190.455 ms 194.000 ms -0.4% no signal
1.2-million-row fetching 3461.402 ms 3461.301 ms +0.4% no signal
Common table expression queries 5.472 ms 5.454 ms -0.3% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.329 ms 1.144 ms -5.8% no signal
10,000 scalar values / fetchval() (debug disabled) 18.939 ms 18.702 ms -2.2% no signal
10,000 output-converted rows / fetchall() 19.460 ms 19.251 ms +0.3% no signal
10,000 output-converted rows / fetchmany(1000) 23.125 ms 23.623 ms +1.9% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 27.154 ms 26.904 ms -0.2% no signal
5,000 x 8 VARCHAR(8000) / ASCII to UTF-16 38.432 ms 43.933 ms +14.5% no signal
5,000 x 8 VARCHAR(8000) / CP1252 to UTF-16 56.142 ms 55.303 ms -2.2% no signal
5,000 x 8 VARCHAR(8000) / UTF-8 to UTF-16 (astral) 104.982 ms 111.953 ms +3.3% no signal
5,000 x 8 NVARCHAR(4000) / UTF-16 (astral) 93.031 ms 79.461 ms -11.7% no signal
5,000 x 8 VARCHAR(8000) / short ASCII 10.165 ms 10.231 ms +1.9% no signal
200 x 8 VARCHAR(8000) / full-width ASCII 44.065 ms 43.458 ms +0.6% no signal
5,000 x 8 VARCHAR(8000) / short CP1252 12.426 ms 12.894 ms +1.6% no signal
200 x 8 VARCHAR(8000) / full-width CP1252 43.376 ms 42.712 ms -2.3% no signal
5,000 x 8 VARCHAR(8000) / short UTF-8 (astral) 16.030 ms 16.137 ms +2.2% no signal
200 x 8 VARCHAR(8000) / full-width UTF-8 (astral) 46.929 ms 46.619 ms -0.3% no signal
5,000 x 8 NVARCHAR(4000) / short UTF-16 (astral) 14.168 ms 13.752 ms -2.4% no signal
200 x 8 NVARCHAR(4000) / full-width UTF-16 (astral) 63.286 ms 67.771 ms +6.3% no signal
200,000 x 8 VARCHAR(32) / fetchall control 513.688 ms 524.066 ms +2.0% no signal
200,000 x 8 INT / fetchall control 274.618 ms 288.928 ms +5.2% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 31.953 ms 31.460 ms -1.5% no signal

Unix / SQL Server 2025

Database task Before After Paired change Result
Connection opening 81.856 ms 80.323 ms -1.0% no signal
SELECT queries 1.223 ms 1.226 ms +0.4% no signal
Row insertion 31.485 ms 31.355 ms -0.3% no signal
Executemany inserts 148.581 ms 148.826 ms +0.1% no signal
Fetch-all queries 119.885 ms 119.726 ms -0.7% no signal
Row-by-row fetching 6.097 ms 5.979 ms -0.9% no signal
Batched row fetching 117.746 ms 118.640 ms +0.9% no signal
Transaction commit and rollback 109.643 ms 107.083 ms -2.3% no signal
Arrow row fetching 89.943 ms 89.945 ms -0.3% no signal
100,000-row insertion 359.425 ms 379.707 ms +5.6% no signal
Row fetching in batches of 100 126.469 ms 125.786 ms -0.2% no signal
Row fetching in batches of 10,000 120.369 ms 133.822 ms +2.7% no signal
Repeated positional queries 32.395 ms 32.576 ms -0.1% no signal
Repeated named-parameter queries 32.979 ms 32.879 ms -0.5% no signal
Legacy 100,000-row insertion 289.009 ms 275.606 ms +1.2% no signal
Insertion with explicit input sizes 411.287 ms 436.687 ms +1.2% no signal
Joined aggregation queries 164.189 ms 163.487 ms -1.0% no signal
Large joined-result fetching 181.547 ms 179.472 ms -1.2% no signal
1.2-million-row fetching 3461.675 ms 3459.222 ms +0.0% no signal
Common table expression queries 5.253 ms 5.239 ms +0.2% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.734 ms 1.699 ms -2.0% no signal
10,000 scalar values / fetchval() (debug disabled) 19.771 ms 19.437 ms -1.8% no signal
10,000 output-converted rows / fetchall() 20.347 ms 20.205 ms -1.1% no signal
10,000 output-converted rows / fetchmany(1000) 23.999 ms 23.864 ms -4.1% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 27.583 ms 27.259 ms -1.4% no signal
5,000 x 8 VARCHAR(8000) / ASCII to UTF-16 50.250 ms 49.192 ms -2.4% no signal
5,000 x 8 VARCHAR(8000) / CP1252 to UTF-16 61.350 ms 61.821 ms +0.8% no signal
5,000 x 8 VARCHAR(8000) / UTF-8 to UTF-16 (astral) 117.613 ms 119.574 ms +0.4% no signal
5,000 x 8 NVARCHAR(4000) / UTF-16 (astral) 124.901 ms 118.066 ms -4.5% no signal
5,000 x 8 VARCHAR(8000) / short ASCII 10.002 ms 10.268 ms +2.6% no signal
200 x 8 VARCHAR(8000) / full-width ASCII 50.440 ms 49.571 ms +0.7% no signal
5,000 x 8 VARCHAR(8000) / short CP1252 12.401 ms 13.135 ms +6.4% no signal
200 x 8 VARCHAR(8000) / full-width CP1252 49.458 ms 49.508 ms +0.2% no signal
5,000 x 8 VARCHAR(8000) / short UTF-8 (astral) 15.764 ms 16.268 ms +3.5% no signal
200 x 8 VARCHAR(8000) / full-width UTF-8 (astral) 52.963 ms 53.161 ms +0.5% no signal
5,000 x 8 NVARCHAR(4000) / short UTF-16 (astral) 14.047 ms 13.682 ms -2.6% no signal
200 x 8 NVARCHAR(4000) / full-width UTF-16 (astral) 73.150 ms 73.471 ms +0.4% no signal
200,000 x 8 VARCHAR(32) / fetchall control 484.017 ms 497.375 ms +1.2% no signal
200,000 x 8 INT / fetchall control 267.159 ms 263.103 ms -1.1% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 30.903 ms 30.743 ms -0.5% no signal
Build and measurement details

ADO build 195487

PR head: 9ad1449fb194aadfd949ecfe81e1441833163850
Base: cfd8b9e69699e5e44d7c1d62115dd8b706ac7985
Measured merge: 6a7a15bc8c7331703f031fa8cf515ccc2c8fde91

  • 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

79%


🎯 Overall Coverage

86%


📈 Total Lines Covered: 13658 out of 15816
📁 Project: mssql-python


Diff Coverage

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

  • mssql_python/pybind/ddbc_bindings.cpp (79.4%): Missing lines 3933,5232,5375,5666-5667,5695,5701-5703,5706-5712,5800,7066,7072-7073

Summary

  • Total: 97 lines
  • Missing: 20 lines
  • Coverage: 79%

mssql_python/pybind/ddbc_bindings.cpp

Lines 3929-3937

  3929             return !IsLobOrVariantColumn(dataType, columnSize);
  3930     }
  3931 }
  3932 
! 3933 static size_t CheckedFetchBufferBytes(size_t count, size_t itemSize, size_t terminator);
  3934 
  3935 static bool IsBoundedFetchText(SQLSMALLINT type, SQLULEN size) {
  3936     return size > 0 && size <= SQL_MAX_LOB_SIZE &&
  3937            (type == SQL_CHAR || type == SQL_VARCHAR || type == SQL_LONGVARCHAR ||

Lines 5228-5236

  5228         SQLSMALLINT dataType;
  5229         SQLULEN columnSize;
  5230         SQLULEN processedColumnSize;
  5231         uint64_t fetchBufferSize;
! 5232         size_t bufferBytes;
  5233         bool isLob;
  5234     };
  5235     const bool useWideChar = (charCtype == SQL_C_WCHAR);
  5236     std::vector<ColumnInfo> columnInfos(numCols);

Lines 5371-5379

  5371             // Performance: Centralized NULL checking before calling processor
  5372             // functions This eliminates redundant NULL checks inside each
  5373             // processor and improves CPU branch prediction
  5374             SQLLEN dataLen = buffers.indicators[col - 1][i];
! 5375             if constexpr (strictLengths)
  5376                 ValidateBoundCellLength(columnInfos[col - 1].dataType, dataLen,
  5377                                         columnInfos[col - 1].bufferBytes,
  5378                                         !buffers.wcharBuffers[col - 1].empty());

Lines 5662-5671

  5662                                        py::handle messages, py::handle converters) {
  5663     PERF_TIMER("FetchReusableTextRows");
  5664     (void)wcharEncoding;
  5665     if (limit == 0)
! 5666         return SQL_SUCCESS;
! 5667     const auto metadata = handle->resultMetadata.snapshot().metadata;
  5668     if (!metadata || metadata->columns.size() != numCols)
  5669         ThrowStdException("Column metadata count does not match result column count");
  5670     const auto& columns = metadata->columns;
  5671     constexpr size_t maximumRows = 1000;

Lines 5691-5699

  5691         }
  5692         ret = FetchBatchData<true>(statement, guard.storage->columns, columns, rows, numCols,
  5693                              guard.storage->rowsFetched, {}, charEncoding, charCtype, messages,
  5694                              converters, rowArray);
! 5695         CheckFetchError(handle, ret);
  5696         if (ret == SQL_NO_DATA)
  5697             break;
  5698         if (!SQL_SUCCEEDED(ret))
  5699             return ret;

Lines 5697-5716

  5697             break;
  5698         if (!SQL_SUCCEEDED(ret))
  5699             return ret;
  5700         const size_t fetched = guard.storage->rowsFetched;
! 5701         size_t bytes = 0;
! 5702         if (!dense)
! 5703             for (size_t column = 0; column < numCols; ++column)
  5704                 for (size_t row = 0; row < fetched; ++row)
  5705                     if (guard.storage->columns.indicators[column][row] >= 0)
! 5706                         bytes +=
! 5707                             static_cast<size_t>(guard.storage->columns.indicators[column][row]);
! 5708         count += fetched;
! 5709         if (!dense && count < limit && fetched == rowArray) {
! 5710             dense = bytes / fetched >= boundBytes / 2;
! 5711             // Dense values benefit from the regular larger rowset budget.
! 5712             const size_t targetRows =
  5713                 dense ? std::clamp<size_t>(denseBudget / boundBytes, 1, maximumRows) : sparseRows;
  5714             const size_t batchRows = std::min(limit - count, targetRows);
  5715             if (batchRows <= boundRows)
  5716                 continue;

Lines 5796-5804

  5796     }
  5797 
  5798     std::vector<SQLUSMALLINT> lobColumns;
  5799     bool singleRowEligible = fetchSize == 1;
! 5800     bool dynamicText = false;
  5801     for (SQLSMALLINT i = 0; i < numCols; i++) {
  5802         const auto& column = columnNames.at(i);
  5803         if (IsLobOrVariantColumn(column.dataType, column.columnSize)) {
  5804             lobColumns.push_back(i + 1);  // 1-based

Lines 7062-7070

  7062         // sql_variant always uses SQLGetData for native type preservation
  7063         if (IsLobOrVariantColumn(dataType, columnSize)) {
  7064             lobColumns.push_back(i + 1);  // 1-based
  7065         }
! 7066         dynamicText = dynamicText ||
  7067                       (IsBoundedFetchText(dataType, columnSize) && columnSize > 256);
  7068     }
  7069 
  7070     // If we have LOBs → fall back to row-by-row fetch + SQLGetData_wrap

Lines 7068-7077

  7068     }
  7069 
  7070     // If we have LOBs → fall back to row-by-row fetch + SQLGetData_wrap
  7071     if (!lobColumns.empty() || dynamicText) {
! 7072         LOG("FetchAll_wrap: LOB columns=%zu, reusable bounded text=%d", lobColumns.size(),
! 7073             dynamicText);
  7074         if (numCols < 0 || columnNames.size() != static_cast<size_t>(numCols)) {
  7075             LOG("FetchAll_wrap: Column metadata count does not match result column count");
  7076             ThrowStdException("Column metadata count does not match result column count");
  7077         }


📋 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: 69.5%
mssql_python._native_fetch.py: 80.1%
mssql_python.pybind.ddbc_bindings.cpp: 80.9%
mssql_python.pybind.row_mapping_cache.hpp: 81.5%
mssql_python.pybind.connection.connection_pool.cpp: 82.5%
mssql_python.pybind.connection.connection.cpp: 84.1%
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

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.

2 participants