Repository navigation
FEAT: Add JSON Arrow fetching and release-gated bulk input - #928
Jahnvi Thakkar (jahnvi480) wants to merge 5 commits into
Conversation
Add native JSON Arrow text fetching and lazy mapped Json snapshots. Keep bulk enablement disabled pending a qualified published Rust runtime, and cover native fetch, source failure, and transaction contracts. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
PR Performance Report✅ No regression detectedNo 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 diagnosticsPhase 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 timingsUnix / SQL Server 2022
Unix / SQL Server 2025
Build and measurement detailsPR head:
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 |
There was a problem hiding this comment.
🟡 Changes recommended
The JSON adaptation helper converts list rows into tuples, bypassing the tuple/Row-only contract for mixed sources containing Json values.
1 open issue
What changed in this PR
Adds native JSON Arrow fetching to the synchronous driver and prepares typed JSON bulk input behind a release gate. This advances related work in #261 without claiming to resolve it; bulk input remains disabled on the current Rust runtime pin.
Changes:
- Fetch native JSON as Arrow
large_string()text through the UTF-16 streaming path. - Add lazy, mapped
Jsonadaptation and document runtime requirements and transaction boundaries. - Require PyArrow 21+ and expand fetching, bulk-input, and producer-failure coverage.
| File | Description |
|---|---|
tests/test_json.py |
Tests JSON Arrow output and gated bulk adaptation. |
tests/test_024_bulkcopy_arrow.py |
Adds JSON producer, schema, and failure-boundary tests. |
tests/test_004_cursor_arrow.py |
Tests native JSON streaming with small reported column sizes. |
tests/conftest.py |
Adds qualified-runtime and JSON-server fixtures. |
setup.py |
Raises the PyArrow extra minimum to 21.0.0. |
README.md |
Documents JSON fetching, bulk release gates, and transaction limits. |
mssql_python/pybind/ddbc_bindings.cpp |
Routes JSON Arrow values through wide-character streaming. |
mssql_python/json.py |
Adds lazy adaptation of mapped Json snapshots. |
mssql_python/cursor.py |
Enables JSON Arrow fetching and gates typed bulk adaptation. |
mssql_python/_pycore_types.pyi |
Declares the internal JSON carrier interface. |
Review effort: Balanced
Pass non-tuple rows through unchanged for native rejection. Add mixed tuple/list regressions for typed JSON and ordinary strings, covering row identity, lazy failure, and active-batch rollback. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
Native JSON Arrow support requires human qualification with a real JSON-capable provider/server and across shipped platforms, because reported tests substituted NVARCHAR metadata rather than exercising actual JSON storage.
No open issues 🎉
1 resolved since last review
Review effort: Balanced
Allow json.dumps only for the reused legacy dictionary and assert exactly one serialization per row, while still rejecting snapshot reserialization and parsing. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
Native JSON round trips remain unverified because validation used simulated metadata and an unpublished Rust wheel, leaving real-server, published-runtime, and cross-platform qualification for human review.
No open issues 🎉
Review effort: Balanced
There was a problem hiding this comment.
🔵 Needs a closer look
Development-only ODBC qualification leaves shipped-provider and macOS coverage unverified, while the unresolved 35.3% CI fetchall slowdown lacks comparable-runtime evidence and requires human assessment.
No open issues 🎉
Review effort: Balanced
📊 Code Coverage Report
Diff CoverageDiff: main...HEAD, staged and unstaged changes
Summary
mssql_python/json.pyLines 96-104 96 for row in rows:
97 if not isinstance(row, tuple):
98 # Preserve invalid row shapes for the native writer to reject.
99 yield row
! 100 continue
101 converted = None
102 for index, value in enumerate(row):
103 if (mapped is None or index in mapped) and type(value) is Json:
104 if converted is None:mssql_python/pybind/ddbc_bindings.cppLines 7464-7472 7464 fixedValueSizes[i] = FixedFetchValueSize(dataType);
7465 columnNullable[i] = (nullable != SQL_NO_NULLS);
7466
7467 if (dataType == SQL_SS_JSON ||
! 7468 ((dataType == SQL_WVARCHAR || dataType == SQL_WLONGVARCHAR || dataType == SQL_VARCHAR ||
7469 dataType == SQL_LONGVARCHAR || dataType == SQL_VARBINARY ||
7470 dataType == SQL_LONGVARBINARY || dataType == SQL_SS_XML || dataType == SQL_SS_UDT) &&
7471 (columnSize == 0 || columnSize == SQL_NO_TOTAL || columnSize > SQL_MAX_LOB_SIZE))) {
7472 hasLobColumns = true;📋 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: 75.4%
mssql_python._native_fetch.py: 80.1%
mssql_python.pybind.row_mapping_cache.hpp: 81.5%
mssql_python.pybind.connection.connection_pool.cpp: 83.7%
mssql_python.pybind.ddbc_bindings.cpp: 83.9%
mssql_python.pybind.connection.connection.cpp: 84.9%
mssql_python.logging.py: 86.8%🔗 Quick Links
|

Work Item / Issue Reference
Summary
Add native JSON Arrow fetching as
large_string()text and prepare lazy, mappedJsonbulk-copy adaptation for the merged Rust contract.json_output.Jsonsnapshots to the internal carrier without parsing, reserializing, look-ahead, or replay. Preserve legacy cells, vector rejection, and exact old-core diagnostic translation.Remaining release gates: The committed Rust pin remains
mssql-python-rs==0.5.0; the typed JSON bulk bridge remains disabled until a published runtime containing both the carrier and fail-fast source handling is qualified and pinned. The combined source builds have now passed real native-JSON integration on Windows and Linux against SQL Server 2025. This used a development-only JSON-capable ODBC preview, not qualification of the shipped provider or a production redistributable. macOS source-build qualification was not run. No full-suite or complete OS/Python/architecture matrix qualification is claimed.Validation
Performance investigation: CI slowdown not yet explained
CI build 196138 reported a +35.3% median paired latency increase for ASCII-medium text
fetchallon SQL Server 2022. Two local base/PR comparisons did not reproduce a consistent regression, but do not establish zero regression or explain the original CI result. No speculative performance fix was committed; production code, benchmark workloads and reporting thresholds remain unchanged.Compared base
df875895484e9219753bb5bdce9f62cfb462692bwith headf1964e3d70662a18ab5d8f170523fc460f0c590f. GitHub confirmed the CI candidate mergef8ebe38c24abf345589e14853f768706fc544002has exactly the same tree as that head. Each revision used separate Release (-O3 -DNDEBUG) builds with native profiling both enabled and compiled out. Fresh processes verified their source/native import paths and profiling mode. Both sides used the identical shipped ODBC 18.6.2.2 library, not the JSON development preview.Used the existing
text_conversion_fetchallworkloads unchanged: eight text columns, 5,000 rows for short/medium payloads and 200 rows for full-width payloads, with stored-byte and every-value correctness checks. Timed only publicfetchall, including row wrapping; setup, query execution, validation and cleanup were excluded. Discarded one warmup pair per mode and alternated base/head order. There were no competing builds during measurement.Values are median paired percentage changes in latency; positive means slower. These are not ratios of marginal medians. No local case meets the existing consistent-regression reporting criterion. Dispersion is substantial: Ubuntu release ASCII-medium base median was 36.31 ms, range 32.68–38.24 ms; head median 36.08 ms, range 31.77–52.78 ms. One of ten pairs exceeded +20%. Chronological paired changes were
+8.09%, -3.02%, -5.73%, -13.61%, -3.40%, +38.02%, +8.09%, +15.17%, +7.65%, +5.60%.In the original CI samples, much of the increase was inside the unchanged
SQLFetchScroll_calltimer. Both revisions made exactly 78 fetch calls and 77 row-construction/metadata batches, also confirmed in every local profiled ASCII-medium sample. This excludes additional fetch calls for that workload; it does not prove a root cause or rule out other effects.Limits: Ubuntu matches CI's client Python/compiler versions, but runs under local Docker/WSL2 rather than the CI host. Local SQL2022 was 16.0.4225.2, versus 16.0.4325.4 in the affected CI run. These experiments do not qualify Windows/macOS/ARM64 performance, Arrow throughput, or bulk-copy throughput. The original CI regression remains unresolved pending reproducible source-level evidence or a comparable affected-environment run; the PR remains draft.
Commands below ran from the Python worktree, with
$Ppointing to the retained local performance-artifact directory. Harness scripts are local artifacts, not repository files:.\.venv\Scripts\python.exe "$P\run_comparison.py" --image mssql-python-perf-928:base-head --label base-head-run1.\.venv\Scripts\python.exe "$P\summarize.py" "$P\base-head-run1".\.venv\Scripts\python.exe "$P\run_comparison.py" --image mssql-python-perf-928:ubuntu-base-head --label ubuntu-base-head-run1 --rounds 11.\.venv\Scripts\python.exe "$P\summarize.py" "$P\ubuntu-base-head-run1"Raw outputs, provenance, build logs, scripts and
performance-report.mdare retained locally underperf-928; nothing was filtered to remove outliers. All task-owned SQL/client/build containers were removed with ownership and absence checks. Local images/evidence were retained, not published. No code change or new commit resulted from this investigation.Real native-JSON source-build qualification
Tested Python production code at
af29814308203e14f1effc46f3eb2b0ae8e773a2with source-built Rust runtimed24a843c11861664395816efa58a129b3f783707. The test-only correction used in the passing runs is now committed asf1964e3d70662a18ab5d8f170523fc460f0c590f; its file hash was verified identical to the tested overlay before and after commit. Publication did not change production code, and no new live run is claimed after the byte-identical commit.Both platforms rebuilt the C++ extension and used PyArrow 21.0.0, SQL Server 2025 17.0.5005.3, and an isolated development-only JSON-capable ODBC preview. The bootstrap verified actual query metadata SQL_JSON=-157, provider/native-library hashes, and the installed Rust wheel's SHA256. These runs used actual JSON server storage, not metadata interposition.
MSSQL_TEST_NATIVE_JSON=1was enabled after the capability probe. The private bulk qualification gate was enabled only inside the source-runtime test process; the production gate remains False.The same 123 case identities ran on Windows and Linux. Coverage includes native
Jsonrow bulk input, plain/canonical Arrow input, actual JSON Arrow output aslarge_string, SQL NULL, Unicode/large payloads, malformed/scalar document rejection, mapped/unmapped cells, producer failures, later-reader schema errors, and persistence of already committed batches. The six old-runtime cases cover typed rejection without tail consumption, diagnostic translation, unrelated-error preservation, and legacy dict/list/string/NULL JSON round trips. These counts include repository tests plus local qualification-only payload/baseline probes; they are not a full repository-suite count and do not qualify TVP or async JSON APIs.Commands and results: the following were run from the retained local qualification-artifact directory. The lifecycle harness, manifests, bootstrap/probes, logs, JUnit and provenance are local test artifacts, not files committed by this PR. The harness injects credentials through the environment and supplies an isolated provider/runtime to the tests.
python .\qualify_json_source_builds.py .\json-windows-qualified.json --output .\json-windows-qualifiedpython .\qualify_json_source_builds.py .\json-linux-qualified.json --output .\json-linux-qualifiedpython .\qualify_json_source_builds.py .\json-linux-baseline-qualified.json --output .\json-linux-baseline-qualifiedThe source-runtime bootstrap calls pytest on
tests/test_json.py,tests/test_024_bulkcopy_arrow.pyand the localqualify_json_payloads.py, selectingbulk_json or json_bulk or bulk_arrow_json or bulk_source_failure or json_arrow_returns or large_unicode_json_bulk or typed_json_invalid_document, with-q --no-cov --tb=short -rsand JUnit output.Exact-source Rust importer/carrier/source-failure regressions also passed on Windows: 89 passed, 446 excluded. With
$Fpointing to the retained qualification-artifact root and the qualified Python environment selected, the command was:Source-built Rust wheel SHA256 values:
2777e457fb7d33186ffae48af150ef23d0557255c1e81f9b59a6a1d2a2153e5fdd9cef10ddaf55651eff695e0d07cc0bf4208ae7767885ce7d45cf4f4ec8c40dThe local runtime identifies as 0.6.0; this is not a published release. No preview binaries, wheels, credentials or test bootstrap were committed or published.
Failures encountered and resolved: the initial Windows exact-head run was 114 passed / 1 failed / 8 skipped. The failure was a test mock globally blocking
json.dumps, including legitimate legacy-dictionary conversion; the narrow correction now in this PR preserves the no-reserialization assertion for typed snapshots. Eight cases initially skipped because the explicit native-JSON test flag was absent, then ran after the real capability probe. The initial Linux 0.5.0 baseline had 3 passes / 3 import failures because that published wheel requireslibssl.so.1.1; genuine OpenSSL 1.1 libraries were added only to the isolated baseline container, with no host install or ABI substitution. The corrected baseline passed 6/6. Original failures and final results were retained separately.All temporary SQL/client containers were removed and their absence verified. No system ODBC installation or production dependency/gate was changed.
Earlier SQL Server 2019 evidence and formatting/typing checks
The earlier Windows x64/Python 3.13.17/PyArrow 21.0.0 checks below are retained for transparency. Native JSON storage cases skipped on SQL Server 2019; the 14-case native Arrow selection used metadata interposition over real SQLGetData. Those earlier results alone were not native-storage qualification; the SQL Server 2025 results above supply that evidence.
.\.venv\Scripts\python.exe -m pytest tests\test_json.py tests\test_020_bulkcopy_auth_cleanup.py tests\test_024_bulkcopy_arrow.py -k 'not TestBulkcopyArrowLive' -q --no-cov.\.venv\Scripts\python.exe -m pytest -p qualified_json_runtime tests\test_json.py tests\test_024_bulkcopy_arrow.py -k 'bulk_source_failure or bulk_arrow_json or bulk_json_native' -q --no-cov.\.venv\Scripts\python.exe -m pytest tests\test_004_cursor_arrow.py -k 'native_json_arrow_streams or test_arrow_lob_wide or test_arrow_nolob_wide or test_arrow_single_column or test_arrow_empty_fetch or test_arrow_long_string' -q --no-cov.\.venv\Scripts\python.exe -m pytest tests\test_typing.py -m typing -q --no-cov.\.venv\Scripts\python.exe -m pre_commit validate-config.\.venv\Scripts\python.exe -m pre_commit run black-check --all-files --hook-stage pre-pushgit diff --checkThe earlier
qualified_json_runtimeplugin is also a local, non-repository test-process gate with exact wheel hash verification, not a production bypass. Commit/push hooks passed forf1964e3d; the PR remains draft.