Skip to content

PERF: single-pass pyformat to qmark conversion, cached per statement - #888

Merged
Jahnvi Thakkar (jahnvi480) merged 3 commits into
microsoft:mainfrom
dxdc:perf/pyformat-single-pass
Nov 12, 2026
Merged

Jahnvi Thakkar (jahnvi480) merged 3 commits into
microsoft:mainfrom
dxdc:perf/pyformat-single-pass

Conversation

@dxdc

Copy link
Copy Markdown
Contributor

Work Item / Issue Reference

GitHub Issue: #500


Summary

Follow-up to #500. SQLAlchemy inserts on mssql-python were still topping out around 20-25K rows/s, and most of that time turned out to be in convert_pyformat_to_qmark(). It did a str.count() + str.replace() over the whole SQL for every parameter, which for a typical SQLAlchemy batch (~2,000 params, ~30 KB of SQL) is ~50 ms per execute().

This rewrites the conversion as a single pass over the placeholder positions the existing scanner already finds, and caches the result per SQL string (small LRU), since the same statement gets executed batch after batch.

It also fixes a few edge cases in the same code:

  • placeholders inside string literals, quoted/bracketed identifiers and comments were getting rewritten (SELECT '%(id)s', %(id)s became SELECT '?', ?)
  • %%(name)s was treated as a placeholder by parse_pyformat_params() but not by the conversion, so executemany() with dict rows could end up with the wrong number of values
  • %% handling no longer relies on a sentinel string, so SQL containing that text isn't changed

Conversion for a 2,000-param statement goes from ~50 ms to ~3 ms (~0.1 ms when cached). SQLAlchemy's default insert into SQL Server went from ~27K to ~189K rows/s in my testing. Added tests for the cases above.

Copilot AI balanced review requested due to automatic review settings November 9, 2026 22:06
@azure-pipelines

Copy link
Copy Markdown
Contributor
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.
@github-actions

github-actions Bot commented Nov 9, 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.

No affected phases or call-count changes were recorded.

All database tasks and timings

Unix / SQL Server 2022

Database task Before After Paired change Result
Connection opening 10.762 ms 10.350 ms -2.3% no signal
SELECT queries 1.082 ms 1.079 ms +4.3% no signal
Row insertion 32.787 ms 32.992 ms +0.6% no signal
Executemany inserts 159.080 ms 160.339 ms -1.1% no signal
Fetch-all queries 119.434 ms 122.430 ms +2.2% no signal
Row-by-row fetching 4.870 ms 4.957 ms +1.6% no signal
Batched row fetching 117.116 ms 117.713 ms +0.4% no signal
Transaction commit and rollback 108.122 ms 110.476 ms +3.1% no signal
Arrow row fetching 89.271 ms 91.091 ms +2.0% no signal
100,000-row insertion 481.810 ms 472.650 ms -0.0% no signal
Row fetching in batches of 100 120.587 ms 121.358 ms +0.4% no signal
Row fetching in batches of 10,000 140.531 ms 137.970 ms +1.6% no signal
Repeated positional queries 33.733 ms 33.938 ms +0.3% no signal
Repeated named-parameter queries 37.411 ms 34.118 ms -8.8% no signal
Legacy 100,000-row insertion 368.146 ms 377.371 ms -0.1% no signal
Insertion with explicit input sizes 493.462 ms 506.746 ms -1.1% no signal
Joined aggregation queries 185.065 ms 194.998 ms +3.2% no signal
Large joined-result fetching 201.347 ms 204.563 ms +1.6% no signal
1.2-million-row fetching 3535.603 ms 3515.981 ms +0.2% no signal
Common table expression queries 5.472 ms 5.467 ms +0.9% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.415 ms 1.459 ms +4.7% no signal
10,000 scalar values / fetchval() (debug disabled) 16.676 ms 16.956 ms +2.1% no signal
10,000 output-converted rows / fetchall() 19.521 ms 19.303 ms -0.2% no signal
10,000 output-converted rows / fetchmany(1000) 24.750 ms 23.727 ms -2.0% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 32.718 ms 32.077 ms -1.9% no signal

Unix / SQL Server 2025

Database task Before After Paired change Result
Connection opening 98.714 ms 98.524 ms -0.2% no signal
SELECT queries 1.013 ms 1.037 ms +3.3% no signal
Row insertion 32.693 ms 32.688 ms +0.4% no signal
Executemany inserts 157.185 ms 156.624 ms +0.6% no signal
Fetch-all queries 123.757 ms 123.106 ms -0.9% no signal
Row-by-row fetching 5.400 ms 5.026 ms -6.9% no signal
Batched row fetching 118.293 ms 118.659 ms +0.3% no signal
Transaction commit and rollback 108.257 ms 108.383 ms -1.1% no signal
Arrow row fetching 90.600 ms 92.790 ms +1.8% no signal
100,000-row insertion 441.917 ms 451.167 ms -0.1% no signal
Row fetching in batches of 100 122.235 ms 126.139 ms +2.5% no signal
Row fetching in batches of 10,000 133.706 ms 141.150 ms +3.9% no signal
Repeated positional queries 34.002 ms 33.723 ms -1.7% no signal
Repeated named-parameter queries 36.066 ms 34.095 ms -6.3% no signal
Legacy 100,000-row insertion 349.886 ms 350.193 ms -0.7% no signal
Insertion with explicit input sizes 480.310 ms 502.032 ms +5.1% no signal
Joined aggregation queries 186.695 ms 167.895 ms -10.4% no signal
Large joined-result fetching 195.387 ms 193.615 ms +0.8% no signal
1.2-million-row fetching 3547.858 ms 3524.695 ms -1.0% no signal
Common table expression queries 5.187 ms 5.167 ms -0.9% no signal
256 KiB VARCHAR(MAX) / fetchall() 2.055 ms 1.949 ms -5.2% no signal
10,000 scalar values / fetchval() (debug disabled) 17.076 ms 17.080 ms +1.0% no signal
10,000 output-converted rows / fetchall() 19.723 ms 19.663 ms -1.7% no signal
10,000 output-converted rows / fetchmany(1000) 23.880 ms 23.393 ms -2.0% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 30.805 ms 33.391 ms +4.3% no signal
Build and measurement details

ADO build 191076

PR head: e36e4a07b0f48a2dce3b8068c9542e389610e646
Base: 730cb2bec05c650b1dba069bf9cbbadb810291d9
Measured merge: 8a80dd09892b9028e503f1175ef794d55884cf70

  • Unix / SQL Server 2022: Python 3.12.3, x86_64, SQL 16.0.4315.2; 5 paired comparisons and 1 warmup.
  • Unix / SQL Server 2025: Python 3.12.3, x86_64, SQL 17.0.5045.3; 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.

@dxdc

Copy link
Copy Markdown
Contributor Author

@microsoft-github-policy-service agree

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

Unavailable native-built, live SQL Server validation and matched base/PR benchmarks leave SQLAlchemy execute(), dict-based executemany(), and claimed throughput gains unverified.

No open issues 🎉

What changed in this PR

This follow-up to #500 optimizes pyformat parameter conversion in the Python driver, targeting repeated, parameter-heavy SQLAlchemy statements.

Changes:

  • Replaces per-parameter SQL replacements with a position-based rewrite and a 32-entry statement cache.
  • Preserves placeholder-like text in quoted SQL and comments, and fixes escaped-percent and sentinel-collision handling.
  • Adds regression tests for large inserts, cache reuse, missing parameters, and parameter-style validation.
File Description
tests/​test_015_pyformat_parameters.py Adds conversion, escaping, validation, and cache-reuse regression tests.
mssql_python/​parameter_helper.py Implements cached, position-based conversion and reduces unnecessary scanning and debug-log preparation.

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 10, 2026 05:47

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.

🟢 Approval recommended

No active review issues are reported for the parameter-conversion optimization.

No open issues 🎉

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 10, 2026 07: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.

🟢 Approval recommended

No active review issues are recorded for the parameter-conversion optimization.

No open issues 🎉

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 11, 2026 08:41
@jahnvi480

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Contributor
Azure Pipelines:
Successfully started running 1 pipeline(s).

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 reported SQLAlchemy throughput gains and execute/executemany behavior require validation with a built driver and live SQL Server, which was unavailable in this source-only review environment.

No open issues 🎉

Review effort: Balanced

@dxdc

Copy link
Copy Markdown
Contributor Author

Thanks for kicking off the pipeline. A note on the performance report, since it shows "no signal" for everything:

The only workload in the suite that goes through the pyformat conversion is "Repeated named-parameter queries" (SELECT %(value)s, one parameter, 100 executes). It did get faster in both environments, 37.4 ms to 34.1 ms on SQL Server 2022 and 36.1 ms to 34.1 ms on SQL Server 2025, which is about 20-30 microseconds saved per execute. That matches what I measured locally for a small statement. It just sits under the 20% threshold because most of that workload is 100 round trips to the server.

The case this PR is really aimed at is a large statement with many named parameters, like the multi-row INSERT that SQLAlchemy emits (about 30 KB of SQL and 2,000 parameters per 1,000 rows). There the conversion goes from roughly 68 ms to about 1 ms on first execution and 0.17 ms on repeat. None of the 25 tasks cover that right now, since the insert workloads use ? placeholders and skip the conversion.

If it would help, I'm happy to add a workload for it to eng/profiler_benchmarks in this PR (same 1,000-row batched insert as the existing one, but with %(name)s placeholders and a dict), or to leave that for a separate PR if you'd rather keep this one small. Just let me know which you prefer.

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.

I compared its head against its base using live SQL Server, with two runs of 24 balanced before/after pairs:

Workload Measured result
2,000 named parameters, cached statement 12.2–12.3× faster
2,000 named parameters, empty conversion cache 8.3–8.5× faster

The mechanism is sound: it removes repeated whole-SQL scans, caches the SQL rewrite—not parameter values—and avoids unnecessary logging work.

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.

LGTM! Thank you so much for your valuable contribution to make our driver faster.

@jahnvi480
Jahnvi Thakkar (jahnvi480) merged commit 01a18f7 into microsoft:main Nov 12, 2026
34 checks passed
Jahnvi Thakkar (jahnvi480) added a commit that referenced this pull request Nov 18, 2026
[AB#50320](https://sqlclientdrivers.visualstudio.com/c6d89619-62de-46a0-8b46-70b92a84d85e/_workitems/edit/50320)

### Summary

Prepare mssql-python 1.18.0 using the approved customer-facing change
inventory since v1.17.0.

#### Enhancements

- Accept APP/Application Name across synchronous, async and bulk-copy
paths; note the async/bulk-copy default application-name change to
MSSQL-Python (#884).
- Reduce row-to-dictionary, single-row fetch, output-converter batch and
fetchmany(1) text-processing overhead (#847, #858, #852, #891).
- Cache single-pass pyformat conversion and retain compatible parameter
bindings for prepared-statement reuse (#888, #886).
- Include mssql-python-rs 0.5.0 improvements: Rust-backed execution,
macOS Strict TLS and table-valued parameters in the opt-in Rust ODBC
provider (#896).

#### Bug Fixes

- Avoid unsupported isolation reset when closing pooled Azure Synapse
connections (#889).
- Respect explicit positive connection timeouts during pooled checkout
(#897).
- Coordinate Arrow reader cross-thread shutdown/cancellation (#892).
- Preserve SQL literal, identifier, comment and escaped-percent behavior
during pyformat conversion (#888).
- Include Rust-backed timeout, prepared-statement lifetime/cancellation,
isolation-change, small-stack connection, streaming-order and
SQL_VARIANT decoding fixes (#896).

#### Version

- Bump mssql_python.__version__ and setup.py from 1.17.0 to 1.18.0.
- Replace the previous PyPI highlights with the approved 1.18.0
inventory.
- Change exactly three release files; no runtime implementation or
dependency-pin changes in this PR.

### Validation

- Passed: pinned full-directory Black check, staged Python formatting
hook, release-version/highlights/approved-PR inventory checks, and git
diff --check.
- Not run locally: native rebuild and full integration suite. The
isolated project environment lacks runtime/test dependencies and
DB_CONNECTION_STRING is unset. No integration-test success is claimed;
release qualification remains required.

### Release gates

- Keep this PR unmerged until the required PyPI and Conda
release/verification gates complete.
- Rust dependency verified: mssql-python-rs==0.5.0 was built
successfully by ADO build 191702 from stable commit 2f6ab0fa…. Release
run 191738 successfully verified/staged and published the wheels through
ESRP. All nine wheels are non-yanked on PyPI, and their advertised
SHA256 digests match the staging log. There is no wheel-build or
publication blocker. The overall release run failed on Guardian findings
and dependency-update automation; any required Guardian disposition
remains separate and unresolved.
- Rust release-source comparison: 0.4.0 at
0c3e3c1436b1234d4e838087ff11140ba68b43a5 to 0.5.0 at
2f6ab0faf2a3a4dbad7dc8f0c4cfe2980eabf41d, verified against version
declarations and ADO release sources.

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jahnvi Thakkar <61936179+jahnvi480@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants