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
Reduce temporary native bound storage for wide-declared text using smaller complete reusable rowsets. This is a memory/driver-call tradeoff, not a demonstrated throughput improvement. Each bound cell still reserves its declared width; fewer rows are bound simultaneously. Python result memory is outside the native rowset target.
Eligible fetchall()/fetchmany() results contain bounded text wider than 256 declared characters and no LOB/variant columns. Target 1 MiB of bound data plus indicators, at most 100 initial rows and 1,000 later, retaining at least one complete row.
Decode directly into actual-length Python results. No extra compact native copy, per-cell length probes, unsupported truncated-rowset recovery, or cursor-type changes. The removed per-cell prototype is no longer the implementation under review.
Full rowsets whose observed payload reaches half the declared row width can grow to the ordinary 8 MiB target. Sparse data keeps the smaller target.
CI follow-ups normalize Python LCOV function locations without changing coverage hit counts, and reduce Arrow test ODBC traffic while retaining real 256 MiB budget crossings.
Review clarification (4e604a49): More batches mean more driver fetch calls, repeated conversion-metadata setup, and indicator scans until dense growth. The README now makes these costs explicit. No production algorithm or budget was changed in response to this comment, and no new latency measurement is claimed.
Historical evidence, not current-head production latency: For 5,000 rows with an integer ID and eight short values declared VARCHAR(8000), the reusable-rowset implementation used about 0.98 MiB of bound data plus indicators versus 7.94 MiB on pinned main, with 626 versus 78 SQLFetchScroll calls (about 88% less bound storage and 8 times as many fetch calls). These are driver calls, not measured network round trips. The removed per-cell prototype made 5,001 SQLFetch plus 45,000 SQLGetData calls; that comparison establishes removal of the prototype bottleneck, not superiority over main.
The 2026-11-27 profiling-disabled Windows comparisons used candidate 2068695b0f268485836fe8e3cd672810719b1060 and base cfd8b9e69699e5e44d7c1d62115dd8b706ac7985, Python 3.13.17, matching MSVC Release builds, SQL Server 15.0.4382.1, and the same ODBC driver DLL. Six counterbalanced fresh-process rounds excluded execute, GC, verification and cleanup from fetch timing. The materialized 50,000-row workload had main/candidate medians 124.56/130.18 ms (candidate 4.5% slower) with substantial variability. Generated-query and materialized results were inconsistent, and unchanged controls also varied. These observations belong to that earlier revision; current-head throughput readiness has not been established. Advisory whole-process memory samples from the earlier implementation are not exact allocation peaks; retained Python results and allocator behavior are outside the bound-storage comparison.
The automated CI performance report uses profiling-enabled builds for attribution. Its detector requires more than 20% median paired movement plus additional consistency conditions. A "no signal" result is not proof of equivalent production-wheel latency and cannot exclude smaller regressions. Repeated, matched, profiling-disabled measurements on the actual candidate and base are required before claiming a throughput benefit or no regression. The 256-character threshold and 1 MiB policy remain experimental.
Validation and limits:
Before the documentation-only follow-up: cmake --build mssql_python\pybind\build\x64\py313 --config Release - passed with the worktree development interpreter and VS 2022 environment, profiling OFF and test interposition ON.
.\.venv\Scripts\python.exe -m pytest tests\test_004_cursor_arrow.py tests\test_017_fetch_buffer_sizing.py tests\test_python_lcov.py --cov=mssql_python --cov-report= -q --disable-warnings --tb=short - 171 passed, 1 skipped, 1 deselected during the CI fix; after the final Arrow workload adjustment, .\.venv\Scripts\python.exe -m pytest tests\test_004_cursor_arrow.py -k 'native_budget' -q --disable-warnings --tb=short - 42 passed, 87 deselected.
Reproduced the exact coverage.py 7.18 / LCOV 2.4 unexpected category UNK renderer failure in an isolated Linux container. Normalization rendered successfully with unchanged line/function hit totals and no ignored errors; python3 -m pytest /repo/tests/test_python_lcov.py /repo/tests/test_pr_code_coverage_workflow.py -q - 21 passed there.
.\.venv\Scripts\python.exe -m pre_commit run black-check --all-files --hook-stage pre-push - passed for the documentation commit; commit/push hooks and git diff --check passed.
No new runtime tests or latency benchmarks for the documentation-only commit. Hosted CI is separate; no claim that the new head is green. Current-head profiling-disabled A/B measurements, production/WAN behavior, alternative providers and local macOS/ARM64 runtime validation remain unverified. Earlier isolated pool/fetch fidelity suites passed; a combined pool-state ordering failure also reproduced on pinned main and was not changed here.
Historical raw observations and provenance remain in the originating session artifacts: reusable-unsampled-comparison.jsonl, reusable-unsampled-report.json, reusable-materialized-comparison.jsonl, reusable-materialized-report.json, reusable-final-driver-counts.json, and matching build/test logs. Benchmark artifacts and native binaries are not committed. Superseded per-revision validation detail remains in the PR history rather than being presented as fresh evidence.
Size bounded fetchall rowsets using checked native buffer bytes and an 8 MiB data-and-indicator target. Start with at most 100 rows and grow once while preserving existing LOB routing and encoding behavior.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
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.
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.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Human assessment is needed because the unconditionally invoked normalizer can crash on valid older LCOV function records, breaking unified coverage generation in some environments.
The reason will be displayed to describe this comment to others. Learn more.
boundBytes cannot be zero on this path. Both callers select FetchReusableTextRows only when the result contains an eligible bounded-text column, so there is at least one column. BoundRowBufferBytes adds each column's checked buffer capacity plus sizeof(SQLLEN) for its indicator; even a zero-capacity cell would therefore contribute a positive amount. Overflow raises rather than wrapping. The metadata count is also checked before calculating the size. No additional zero guard is needed for the current callers.
The reason will be displayed to describe this comment to others. Learn more.
The driver can report zero, but it cannot reach this division. This loop calls FetchBatchData<true>, which resets the fetched count before the driver call and rejects a successful fetch when numRowsFetched == 0 (or exceeds the configured rowset), raising Invalid bounded fetch row count before conversion and before returning here. SQL_NO_DATA breaks the loop before this point, and errors also do not reach the division.
The existing compact-zero-rows case in tests/test_017_fetch_buffer_sizing.py injects a successful driver response with a zero fetched count and asserts that exception. No additional check is needed here.
The reason will be displayed to describe this comment to others. Learn more.
[Blocking]: boundRows is getting modified here by batchRows but configuredRows holds old boundRows value. Hence shall we also correct the configuredRows here?
The reason will be displayed to describe this comment to others. Learn more.
configuredRows intentionally keeps the currently installed SQL_ATTR_ROW_ARRAY_SIZE; boundRows is the capacity of the newly allocated buffers. SQLBindColums does not update the statement's row-array size. At the top of the next iteration, rowArray = min(boundRows, limit - count) differs from configuredRows, so guard.setRowArraySize(rowArray) updates the driver before the next fetch, and only then is configuredRows updated.
Assigning configuredRows = batchRows here without setting the driver attribute would incorrectly skip that required update. The existing growth contract tests check the observed driver rowset sizes and the unbind-before-rebind ordering. No code change is needed.
The reason will be displayed to describe this comment to others. Learn more.
An additional local catch is not needed here. SQLBindColums already raises on a failed column binding (Failed to bind column ...), and the FetchStateGuard is constructed before binding. If binding or allocation throws, stack unwinding runs the guard's destructor to reset the row-array size, clear the fetched-count pointer and unbind columns. Cleanup failures are reported without replacing the original exception, and native storage is retained if cleanup cannot safely release driver references. The exception then propagates to Python rather than continuing with a partial binding.
The existing compact-dense-rebind-failure test injects a failure during this growth rebind; partial-binding and persistent-cleanup-failure cases also exercise recovery and storage lifetime. No code change is needed.
Prepare column conversion metadata once per reusable-rowset call and avoid unnecessary density scans while retaining existing rowset budgets and full-width bindings.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Grow once to the ordinary rowset target after a full initial batch, remove density scans, and assert bounded startup storage and sustained driver-call counts. Document the remaining memory and latency tradeoffs.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
The PR description and review clarification overstate sustained memory savings and need to accurately describe density-independent batch growth, startup/short-result savings, and conversion metadata prepared once per native call.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
The PR description misstates the implemented unconditional buffer-growth policy, incorrectly promising sparse-data memory limits and density-based growth, and must be updated.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
The PR description promises sparse-result memory savings, but the implementation grows after any full batch regardless of payload density, misrepresenting the memory/call tradeoff.
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
Reduce temporary native bound storage for wide-declared text using smaller complete reusable rowsets. This is a memory/driver-call tradeoff, not a demonstrated throughput improvement. Each bound cell still reserves its declared width; fewer rows are bound simultaneously. Python result memory is outside the native rowset target.
fetchall()/fetchmany()results contain bounded text wider than 256 declared characters and no LOB/variant columns. Target 1 MiB of bound data plus indicators, at most 100 initial rows and 1,000 later, retaining at least one complete row.Review clarification (
4e604a49): More batches mean more driver fetch calls, repeated conversion-metadata setup, and indicator scans until dense growth. The README now makes these costs explicit. No production algorithm or budget was changed in response to this comment, and no new latency measurement is claimed.Historical evidence, not current-head production latency: For 5,000 rows with an integer ID and eight short values declared
VARCHAR(8000), the reusable-rowset implementation used about 0.98 MiB of bound data plus indicators versus 7.94 MiB on pinned main, with 626 versus 78SQLFetchScrollcalls (about 88% less bound storage and 8 times as many fetch calls). These are driver calls, not measured network round trips. The removed per-cell prototype made 5,001SQLFetchplus 45,000SQLGetDatacalls; that comparison establishes removal of the prototype bottleneck, not superiority over main.The 2026-11-27 profiling-disabled Windows comparisons used candidate
2068695b0f268485836fe8e3cd672810719b1060and basecfd8b9e69699e5e44d7c1d62115dd8b706ac7985, Python 3.13.17, matching MSVC Release builds, SQL Server 15.0.4382.1, and the same ODBC driver DLL. Six counterbalanced fresh-process rounds excluded execute, GC, verification and cleanup from fetch timing. The materialized 50,000-row workload had main/candidate medians 124.56/130.18 ms (candidate 4.5% slower) with substantial variability. Generated-query and materialized results were inconsistent, and unchanged controls also varied. These observations belong to that earlier revision; current-head throughput readiness has not been established. Advisory whole-process memory samples from the earlier implementation are not exact allocation peaks; retained Python results and allocator behavior are outside the bound-storage comparison.The automated CI performance report uses profiling-enabled builds for attribution. Its detector requires more than 20% median paired movement plus additional consistency conditions. A "no signal" result is not proof of equivalent production-wheel latency and cannot exclude smaller regressions. Repeated, matched, profiling-disabled measurements on the actual candidate and base are required before claiming a throughput benefit or no regression. The 256-character threshold and 1 MiB policy remain experimental.
Validation and limits:
cmake --build mssql_python\pybind\build\x64\py313 --config Release- passed with the worktree development interpreter and VS 2022 environment, profiling OFF and test interposition ON..\.venv\Scripts\python.exe -m pytest tests\test_004_cursor_arrow.py tests\test_017_fetch_buffer_sizing.py tests\test_python_lcov.py --cov=mssql_python --cov-report= -q --disable-warnings --tb=short- 171 passed, 1 skipped, 1 deselected during the CI fix; after the final Arrow workload adjustment,.\.venv\Scripts\python.exe -m pytest tests\test_004_cursor_arrow.py -k 'native_budget' -q --disable-warnings --tb=short- 42 passed, 87 deselected.unexpected category UNKrenderer failure in an isolated Linux container. Normalization rendered successfully with unchanged line/function hit totals and no ignored errors;python3 -m pytest /repo/tests/test_python_lcov.py /repo/tests/test_pr_code_coverage_workflow.py -q- 21 passed there..\.venv\Scripts\python.exe -m pre_commit run black-check --all-files --hook-stage pre-push- passed for the documentation commit; commit/push hooks andgit diff --checkpassed.Historical raw observations and provenance remain in the originating session artifacts:
reusable-unsampled-comparison.jsonl,reusable-unsampled-report.json,reusable-materialized-comparison.jsonl,reusable-materialized-report.json,reusable-final-driver-counts.json, and matching build/test logs. Benchmark artifacts and native binaries are not committed. Superseded per-revision validation detail remains in the PR history rather than being presented as fresh evidence.