You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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>
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>
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.
7062// sql_variant always uses SQLGetData for native type preservation7063if (IsLobOrVariantColumn(dataType, columnSize)) {
7064 lobColumns.push_back(i + 1); // 1-based7065 }
! 7066 dynamicText = dynamicText ||
7067 (IsBoundedFetchText(dataType, columnSize) && columnSize > 256);
7068 }
70697070// If we have LOBs → fall back to row-by-row fetch + SQLGetData_wrap
Lines 7068-7077
7068 }
70697070// If we have LOBs → fall back to row-by-row fetch + SQLGetData_wrap7071if (!lobColumns.empty() || dynamicText) {
! 7072LOG("FetchAll_wrap: LOB columns=%zu, reusable bounded text=%d", lobColumns.size(),
! 7073 dynamicText);
7074if (numCols < 0 || columnNames.size() != static_cast<size_t>(numCols)) {
7075LOG("FetchAll_wrap: Column metadata count does not match result column count");
7076ThrowStdException("Column metadata count does not match result column count");
7077 }
📋 Files Needing Attention
📉 Files with overall lowest coverage (click to expand)
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>
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.
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.
…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>
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
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.
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.
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Work Item / Issue Reference
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
SQLGetDatarecovery.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.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 as2068695b0f268485836fe8e3cd672810719b1060. The PR targetsmain. 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,001SQLFetchplus 45,000SQLGetDatacalls. The replacement makes 626SQLFetchScroll, zeroSQLFetch, and zeroSQLGetDatacalls. Pinned main makes 78SQLFetchScrollcalls. 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 Releasepassed, 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-pushand 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 at7362ec45, 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 andmsodbcsql1818.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.VARCHAR(8000)VARCHAR(8000)VARCHAR(8000)rowsVARCHAR(32)control rowsBIGINTcontrol rowsThe 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 --checkandgit diff --checkpassed; 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 reachedfailure 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, andreusable-boundary-json-regressions.log.