Skip to content

Commit cfd8b9e

Browse files
jahnvi480Copilot
andauthored
PERF: reduce fetchall buffer over-allocation (#919)
### Work Item / Issue Reference <!-- IMPORTANT: Please follow the PR template guidelines below. For mssql-python maintainers: Insert your ADO Work Item ID below For external contributors: Insert Github Issue number below Only one reference is required - either GitHub issue OR ADO Work Item. --> <!-- mssql-python maintainers: ADO Work Item --> > ADO Work Item: N/A <!-- External contributors: GitHub Issue --> > GitHub Issue: #455 ------------------------------------------------------------------- ### Summary <!-- Insert your summary of changes below. Minimum 10 characters required. --> This pull request introduces several important enhancements and fixes to the profiler benchmarks and the native driver, primarily focused on adding comprehensive text conversion workloads and improving resource management after batch fetch failures. The changes also include updates to documentation and internal naming for clarity. **Profiler benchmark enhancements:** * Added new workloads to the profiler benchmark suite for text conversion, covering ASCII, CP1252, UTF-8, and NVARCHAR scenarios, including variants for short and full payloads, as well as narrow control fetches for both VARCHAR and INT types. These workloads measure performance and correctness of text decoding and buffer management. * Updated the profiler benchmark documentation to describe the new text conversion workloads, their setup, and their validation approach, and to reflect the expanded registry of 40 tasks. **Driver resource management and error handling:** * Improved handling of failed batch fetch cleanup: renamed internal structures from `FailedParameterBuffers` to `FailedBindingBuffers` for clarity, ensured that failed batches retire the statement and retain native buffers until explicit release or disconnect, and introduced a new exception (`RetiredStatementError`) to signal use of retired statements. * Enhanced buffer allocation logic for column binding, including stricter size checks and more accurate buffer sizing for various data types and character encodings during fetch operations. **Changelog update:** * Documented the changes to `fetchall()` batch sizing and the new handling of cleanup failures in the project changelog. --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent f3e19e9 commit cfd8b9e

10 files changed

Lines changed: 1002 additions & 205 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,19 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66

77
## [Unreleased]
88

9+
### Changed
10+
- `fetchall()` starts bounded-column fetching with at most 100 rows, growing
11+
once after a full batch to at most 1,000 rows. Batch sizing targets 8 MiB
12+
of native column data and length/null indicators, accounting for character
13+
conversion and terminators; a single wider row is still allowed. This is
14+
not a limit on retained Python results or total process memory. Declared-width
15+
string buffers and the existing LOB streaming path remain unchanged (#455,
16+
partially addressed). Smaller rowsets can increase driver fetch calls; these
17+
calls do not necessarily correspond to network round trips.
18+
- Batch fetch cleanup failures retire the statement and retain native column,
19+
indicator, and rows-fetched storage until successful statement release or
20+
connection disconnect, including partially rebound batches.
21+
922
### Added
1023
- Preview synchronous native JSON support with immutable `Json(dict | list | str)`
1124
inputs, `SQL_JSON` / `SQL_SS_JSON` binding, typed NULLs and large-value streaming.

‎eng/profiler_benchmarks/README.md‎

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ python -m eng.profiler_benchmarks.controller --base main --candidate HEAD \
1212
python -m eng.profiler_benchmarks.report profiler-results/report.json
1313
```
1414

15-
The fixed registry has 26 tasks. `--scenarios` runs a local subset, but subset
15+
The fixed registry has 40 tasks. `--scenarios` runs a local subset, but subset
1616
reports remain incomplete and cannot produce a verdict.
1717

1818
`lob_varchar_256k_fetchall` fetches one 256 KiB `VARCHAR(MAX)` value to exercise
@@ -67,9 +67,41 @@ preparation, key/order/value/type/NULL checks, row counts, cursor diagnostics,
6767
and cleanup are excluded. This is one additional workload, not a cold/warm or
6868
width matrix.
6969

70-
This conversion has no guaranteed instrumented native phase, so **only**
70+
`text_conversion_{ascii,cp1252,utf8,nvarchar}_fetchall` adds four matched text-fetch
71+
workloads: 5,000 rows, eight declared-wide columns, and 256-character payloads.
72+
ASCII is a control; CP1252 includes accented text and the euro sign; UTF-8 VARCHAR
73+
and NVARCHAR include BMP and supplementary characters. Each workload requires
74+
UTF-16LE / SQL_WCHAR decoding. VARCHAR columns are declared as VARCHAR(8000);
75+
NVARCHAR columns are NVARCHAR(4000). The UTF-8 case requires SQL Server 2019+
76+
UTF-8 collation support; unsupported setup fails rather than reporting a speedup.
77+
78+
Connection-local temporary-table creation, population, stored-byte verification,
79+
query execution, output validation, and cleanup are outside timing. Only public
80+
`fetchall()` and retained row construction are timed. Stored-byte checks prevent
81+
lossy insertion or an unintended source encoding from masquerading as conversion
82+
coverage. All four run identically on base and candidate with the existing paired
83+
report thresholds. Driver conversion is included in the fetch-call phase; Python
84+
Unicode construction is included in row construction, not a separately isolated
85+
decoder timer. Python strings use flexible-width storage, not uniformly UTF-32.
86+
These are local/server-specific conversion workloads, not a WAN simulation.
87+
88+
The `_short_fetchall` and `_full_fetchall` variants use the same four storage
89+
types. Short values have eight characters and 5,000 rows. Near-full values repeat
90+
whole patterns up to the column's 8,000-byte stored-data limit and use 200 rows
91+
to bound retained output memory. Supplementary characters therefore consume
92+
different numbers of UTF-8 bytes and UTF-16 code units; the payload limit is not
93+
calculated using Python code-point counts. The source Unicode literal is MAX
94+
only during insertion; the measured result columns remain bounded types.
95+
96+
`narrow_varchar_fetchall` and `narrow_integer_fetchall` each fetch 200,000 rows
97+
and eight columns. The first uses short VARCHAR(32) values; the second uses
98+
ordered INT values. Both exclude query execution and validate every returned
99+
value/type outside the fetch timer. These controls target initial rowset growth
100+
and shared setup costs without large declared string allocations.
101+
102+
The row-to-dictionary workload has no guaranteed instrumented native phase, so **only**
71103
`row_to_dict` permits an empty native diagnostics dictionary. Skipped results,
72-
malformed counters, and missing native samples from the other 25 tasks remain
104+
malformed counters, and missing native samples from the other 39 tasks remain
73105
invalid in both the worker and report validation. The row uses the existing
74106
paired wall-time comparison and unchanged thresholds: it can demonstrate an
75107
observed main-relative improvement, not assert a speedup in advance or establish

‎eng/profiler_benchmarks/report.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,20 @@
4242
"output_converter_fetchall": "10,000 output-converted rows / fetchall()",
4343
"output_converter_fetchmany1000": "10,000 output-converted rows / fetchmany(1000)",
4444
"fetchmany_one_text": "10,000 INT/NVARCHAR rows / fetchmany(1)",
45+
"text_conversion_ascii_fetchall": "5,000 x 8 VARCHAR(8000) / ASCII to UTF-16",
46+
"text_conversion_cp1252_fetchall": "5,000 x 8 VARCHAR(8000) / CP1252 to UTF-16",
47+
"text_conversion_utf8_fetchall": "5,000 x 8 VARCHAR(8000) / UTF-8 to UTF-16 (astral)",
48+
"text_conversion_nvarchar_fetchall": "5,000 x 8 NVARCHAR(4000) / UTF-16 (astral)",
49+
"text_conversion_ascii_short_fetchall": "5,000 x 8 VARCHAR(8000) / short ASCII",
50+
"text_conversion_ascii_full_fetchall": "200 x 8 VARCHAR(8000) / full-width ASCII",
51+
"text_conversion_cp1252_short_fetchall": "5,000 x 8 VARCHAR(8000) / short CP1252",
52+
"text_conversion_cp1252_full_fetchall": "200 x 8 VARCHAR(8000) / full-width CP1252",
53+
"text_conversion_utf8_short_fetchall": "5,000 x 8 VARCHAR(8000) / short UTF-8 (astral)",
54+
"text_conversion_utf8_full_fetchall": "200 x 8 VARCHAR(8000) / full-width UTF-8 (astral)",
55+
"text_conversion_nvarchar_short_fetchall": "5,000 x 8 NVARCHAR(4000) / short UTF-16 (astral)",
56+
"text_conversion_nvarchar_full_fetchall": "200 x 8 NVARCHAR(4000) / full-width UTF-16 (astral)",
57+
"narrow_varchar_fetchall": "200,000 x 8 VARCHAR(32) / fetchall control",
58+
"narrow_integer_fetchall": "200,000 x 8 INT / fetchall control",
4559
"row_to_dict": "10,000 rows x 32 columns / dict(row._mapping) (warm)",
4660
}
4761
CASES = tuple(TASK_NAMES)

‎eng/profiler_benchmarks/workloads.py‎

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,133 @@ def converter(raw):
267267
conn.add_output_converter(SQL_WVARCHAR, previous)
268268

269269

270+
def text_conversion_fetchall(conn, ctx, storage, payload_size="medium"):
271+
"""Fetch declared-wide text with stored-byte evidence and explicit UTF-16 decoding."""
272+
from mssql_python import SQL_CHAR, SQL_WCHAR
273+
274+
data_type, collation, encoding, text = {
275+
"ascii": ("varchar(8000)", "Latin1_General_100_BIN2", "ascii", "Abcd1234"),
276+
"cp1252": (
277+
"varchar(8000)",
278+
"Latin1_General_100_BIN2",
279+
"cp1252",
280+
"caf\u00e9 \u20ac\u00df!",
281+
),
282+
"utf8": (
283+
"varchar(8000)",
284+
"Latin1_General_100_BIN2_UTF8",
285+
"utf-8",
286+
"A\u00e9\u4e2d\U0001f642Z\u6f22\u03a9!",
287+
),
288+
"nvarchar": (
289+
"nvarchar(4000)",
290+
"Latin1_General_100_BIN2",
291+
"utf-16le",
292+
"A\u00e9\u4e2d\U0001f642Z\u6f22\u03a9!",
293+
),
294+
}[storage]
295+
for sql_type in (SQL_CHAR, SQL_WCHAR):
296+
if conn.getdecoding(sql_type) != {"encoding": "utf-16le", "ctype": SQL_WCHAR}:
297+
raise ValueError("Text conversion benchmarks require UTF-16LE / SQL_WCHAR decoding")
298+
repeats = {"short": 1, "medium": 32, "full": 8000 // len(text.encode(encoding))}
299+
expected = text * repeats[payload_size]
300+
row_count = 200 if payload_size == "full" else 5000
301+
expected_bytes = expected.encode(encoding)
302+
literal = f"CAST(0x{expected.encode('utf-16le').hex()} AS nvarchar(max))"
303+
with conn.cursor() as cursor:
304+
created = False
305+
try:
306+
cursor.execute(
307+
"CREATE TABLE #ci_text_conversion "
308+
f"(id INT PRIMARY KEY, payload {data_type} COLLATE {collation})"
309+
)
310+
created = True
311+
cursor.execute(
312+
"WITH d(n) AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4),"
313+
"(5),(6),(7),(8),(9)) AS v(n)), "
314+
"nums(n) AS (SELECT a.n+10*b.n+100*c.n+1000*e.n "
315+
"FROM d a CROSS JOIN d b CROSS JOIN d c CROSS JOIN d e) "
316+
f"INSERT INTO #ci_text_conversion SELECT n, {literal} "
317+
f"FROM nums WHERE n < {row_count}"
318+
)
319+
cursor.execute(
320+
"SELECT DATALENGTH(payload), CAST(payload AS varbinary(8000)) "
321+
"FROM #ci_text_conversion WHERE id = 0"
322+
)
323+
assert tuple(cursor.fetchone()) == (len(expected_bytes), expected_bytes)
324+
cursor.execute(
325+
"SELECT "
326+
+ ", ".join(f"payload AS c{column}" for column in range(8))
327+
+ " FROM #ci_text_conversion ORDER BY id"
328+
)
329+
ctx.enable()
330+
start = time.perf_counter()
331+
rows = cursor.fetchall()
332+
wall_ms = (time.perf_counter() - start) * 1000
333+
cpp, py = ctx.collect()
334+
assert len(rows) == row_count
335+
assert all(
336+
tuple(row) == (expected,) * 8 and all(type(value) is str for value in row)
337+
for row in rows
338+
)
339+
assert not cursor.messages, "Clean text conversion unexpectedly produced diagnostics"
340+
return dict(
341+
title="Wide-declared text conversion / fetchall",
342+
wall_ms=wall_ms,
343+
cpp=cpp,
344+
py=py,
345+
detail=(
346+
f"Rows: {row_count}; columns: 8; storage: {data_type}/{encoding}; "
347+
f"payload chars: {len(expected)}; fetch: UTF-16LE; API: fetchall"
348+
),
349+
)
350+
finally:
351+
ctx.disable()
352+
if created:
353+
cursor.execute("DROP TABLE #ci_text_conversion")
354+
355+
356+
def narrow_fetchall_control(conn, ctx, integers=False):
357+
"""Fetch 200,000 narrow rows; only fetching and row wrapping are timed."""
358+
expression = "n" if integers else "CAST('control' AS varchar(32))"
359+
with conn.cursor() as cursor:
360+
cursor.execute(
361+
"WITH d(n) AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4),"
362+
"(5),(6),(7),(8),(9)) AS v(n)), "
363+
"nums(n) AS (SELECT a.n+10*b.n+100*c.n+1000*e.n+10000*f.n+100000*g.n "
364+
"FROM d a CROSS JOIN d b CROSS JOIN d c CROSS JOIN d e "
365+
"CROSS JOIN d f CROSS JOIN d g) SELECT "
366+
+ ", ".join(f"{expression} AS c{column}" for column in range(8))
367+
+ " FROM nums WHERE n < 200000 ORDER BY n"
368+
)
369+
ctx.enable()
370+
try:
371+
start = time.perf_counter()
372+
rows = cursor.fetchall()
373+
wall_ms = (time.perf_counter() - start) * 1000
374+
cpp, py = ctx.collect()
375+
assert len(rows) == 200_000
376+
expected_type = int if integers else str
377+
assert all(
378+
tuple(row) == ((index if integers else "control"),) * 8
379+
and all(type(value) is expected_type for value in row)
380+
for index, row in enumerate(rows)
381+
)
382+
assert not cursor.messages, "Clean narrow fetch unexpectedly produced diagnostics"
383+
return dict(
384+
title="Narrow-result fetchall control",
385+
wall_ms=wall_ms,
386+
cpp=cpp,
387+
py=py,
388+
detail=(
389+
"Rows: 200000; columns: 8; "
390+
f"type: {'int' if integers else 'varchar(32)'}; API: fetchall"
391+
),
392+
)
393+
finally:
394+
ctx.disable()
395+
396+
270397
def row_to_dict(conn, table, ctx):
271398
"""Convert fetched rows with warm mapping metadata; fetch and validation are not timed."""
272399
names = tuple(f"c{column}" for column in range(32))
@@ -336,5 +463,18 @@ def registry():
336463
result["output_converter_fetchall"] = (output_converter_fetch, True)
337464
result["output_converter_fetchmany1000"] = (partial(output_converter_fetch, batched=True), True)
338465
result["fetchmany_one_text"] = (fetchmany_one_text, True)
466+
for storage in ("ascii", "cp1252", "utf8", "nvarchar"):
467+
result[f"text_conversion_{storage}_fetchall"] = (
468+
partial(text_conversion_fetchall, storage=storage),
469+
False,
470+
)
471+
for storage in ("ascii", "cp1252", "utf8", "nvarchar"):
472+
for size in ("short", "full"):
473+
result[f"text_conversion_{storage}_{size}_fetchall"] = (
474+
partial(text_conversion_fetchall, storage=storage, payload_size=size),
475+
False,
476+
)
477+
result["narrow_varchar_fetchall"] = (narrow_fetchall_control, False)
478+
result["narrow_integer_fetchall"] = (partial(narrow_fetchall_control, integers=True), False)
339479
result["row_to_dict"] = (row_to_dict, True)
340480
return result

‎mssql_python/pybind/connection/connection.cpp‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -174,10 +174,10 @@ void Connection::disconnect(bool rollbackBeforeDisconnect) {
174174
for (const auto& handle : childHandles) {
175175
handle->markImplicitlyFreed();
176176
}
177-
for (const auto& buffers : _cleanupState->failedParameterBuffers) {
177+
for (const auto& buffers : _cleanupState->failedBindingBuffers) {
178178
buffers->release();
179179
}
180-
_cleanupState->failedParameterBuffers.clear();
180+
_cleanupState->failedBindingBuffers.clear();
181181
_childStatementHandles.clear();
182182
_allocationsSinceCompaction = 0;
183183
}

0 commit comments

Comments
 (0)