Skip to content

perf(python): return small results as Python rows without pyarrow - #467

Open
vuanhphung wants to merge 7 commits into
mainfrom
perf/rd-rows-native
Open

vuanhphung wants to merge 7 commits into
mainfrom
perf/rd-rows-native

Conversation

@vuanhphung

@vuanhphung vuanhphung commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

For a small result, the Python connector spends more GIL-held time on handling the result than on anything else: arrow_schema() and each fetch_next_batch() export the schema or batch over the C data interface and pyarrow imports it (each import releases and re-takes the GIL), the connector compares schemas with Schema.equals(check_metadata=True) (C++ metadata fingerprints on every call), and then runs to_pylist() per column. A one-process client running SELECT 1 on 800 threads is GIL-bound, and that path was about half of its GIL-held time, plus 6 of its 7 GIL releases per query.

This adds, on ExecutedStatement and ResultStream:

  • fetch_all_rows(max_rows, nan_ok=False): all remaining rows as a list of tuples of Python values built in Rust, with the values pyarrow's to_pylist() returns (ints of every width, floats, bool, null, string, binary and fixed-size binary, decimal128/256, date32, and second/milli/microsecond timestamps with or without a zone, which is resolved with pyarrow's own string_to_tzinfo). It returns None when more than max_rows rows remain, a column has another type, a float is NaN (unless nan_ok) or a value is outside Python's date/datetime range; fetch_next_batch / fetch_all_arrow then return the batches it already read.
  • schema_key(): a hashable SchemaKey that compares two results' schemas (names, types, nullability, metadata) in Rust, so callers can cache what they derive from a schema without building a pyarrow.Schema.

_rows_from_arrow runs the same conversion on pyarrow batches for parity tests and is not public API. The connector change that uses this is databricks/databricks-sql-python#1061. This PR has no dependencies. With #458, fetch_all_rows should read in-memory batches with the GIL held as fetch_next_batch does there; that is one more commit (d58c5eb on perf/rd-rows-native-on-458, stacked on #458), which I'll add here or as a follow-up once #458 is merged. Without it, fetch_all_rows releases the GIL once to read the batch.

Testing. cargo test (new unit tests for the conversion, declines and the pending-batch hand-off), clippy, and tests/test_rows.py: every converted type against to_pylist() with edge values (integer bounds, -0.0, inf, decimal precision 38/76 and negative scale, dates and timestamps at Python's bounds, before the epoch, DST transitions, fixed offsets), a randomized 500-row batch, 18 declined types and values, plus live tests for SELECT, a 1000-row result handed back to the Arrow fetches, a nested type and a metadata stream (the full pytest suite, live tier included, passes against a Real-Time warehouse). The connector's parity suite (#1048's columns against its pandas path) also passes against this wheel, with and without pytz installed.

GIL releases per SELECT 1 query on one connection (perf hardware breakpoint on PyEval_SaveThread, local mock server; connector databricks/databricks-sql-python#1061):

kernel fetchall fetchone
main + #458 and the other factory PRs (connector without the change) 7 8
this PR alone 3 3
this PR + #458 (d58c5eb) 1 1

Live: SELECT 1, 1 process x 800 sessions, 60 s, staging X-Large Real-Time warehouse, 8 client cores, interleaved; kernel = main db23442 + #453 #455 #456 #457 #458 #459 #461, with and without this PR plus d58c5eb; connector = databricks/databricks-sql-python#1059, with and without databricks/databricks-sql-python#1061. Median (min-max) of 3 rounds:

before with the change
Average QPS (setup included) 4520 (4491-4554) 7513 (7344-7562)
Peak QPS (best second) 5059 (4983-5135) 8550 (8506-8652)
Steady QPS (after all sessions open) 4639 (4607-4660) 7698 (7525-7749)
Query latency p50 / p99 (ms) 154 / 424 95 / 230
Client CPU per query (ms) 0.76 (0.75-0.77) 0.44 (0.44-0.44)
Errors 0 0

Average QPS change per round: +67%, +61%, +67%. A fourth run with the change (7629 QPS) is left out because the run it was paired with started on a stopped warehouse.

This pull request and its description were written by Isaac.

A one-row result costs the Python driver far more than the row: importing
the pyarrow schema and batch over the C data interface (each import
releases and re-takes the GIL), a metadata-fingerprinting schema comparison,
and to_pylist() per column.

ExecutedStatement.fetch_all_rows(max_rows, nan_ok) and the same on
ResultStream return all remaining rows as tuples of Python values built in
Rust, equal to what pyarrow's to_pylist() returns for the types they convert
(ints, floats, bool, null, strings, binary, decimal, date32, and s/ms/us
timestamps with or without a time zone). They return None for larger
results, other types, NaN (unless nan_ok) and values outside Python's date
range, and the Arrow fetches then return the batches already read.
schema_key() returns a SchemaKey that compares two results' schemas in Rust,
so callers can cache what they derive from a schema without building a
pyarrow.Schema.

Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
Co-authored-by: Isaac <no-reply@databricks.com>

@oss-reviewer-bot oss-reviewer-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: 2 Low

The change looks correct. The pending-batch hand-off between fetch_all_rows and the Arrow fetches is consistent across fetch_next_batch, fetch_all_arrow and cancel, and null slots are checked before values are read. There are 2 low findings: Python errors are swallowed during conversion, and the fill/hand-off path has no non-live test. Nits: pending.push_back(rb.clone()) in fill/fill_exec clones a batch the code already owns. The two fill functions could share one generic helper. SchemaKey.__eq__ returns False instead of NotImplemented for non-SchemaKey operands.

Comment thread pyo3/src/rows.rs Resolved
Comment thread pyo3/src/fetch.rs Resolved
…ff offline

Review feedback: the row conversion now declines only on OverflowError /
ValueError (a date or datetime out of range) and propagates any other Python
error. SchemaKey.__eq__ returns NotImplemented for other types. New offline
tests drive fetch_all_rows against a local server, for an ExecutedStatement
and a ResultStream: reading to the end, declining at several limits with the
batches then returned by fetch_next_batch / fetch_all_arrow, and
fetch_all_rows after an Arrow fetch.

Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
Co-authored-by: Isaac <no-reply@databricks.com>

@oss-reviewer-bot oss-reviewer-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: 1 Low · 1 Nit

Looks good overall, with two low-severity notes. The hand-off of pending batches between fetch_all_rows, fetch_next_batch and fetch_all_arrow holds up when calls repeat, when the stream ends, and when close() is called. The fallback rules for type support are conservative, and the tests compare results against to_pylist() thoroughly.

Other findings

  • ⚪ Nit — Both let Ok(..) else { return Ok(false) } arms throw away whatever exception they get. Swallowing the ImportError when pyarrow is missing is deliberate. But KeyboardInterrupt, MemoryError, or an unexpected bug inside string_to_tzinfo is also turned into a silent fallback to the Arrow path. The fallback then calls the same tz resolution again inside pyarrow, so the cause gets hidden or raised a second time. Consider declining only for the expected exception types (ImportError on the import; ValueError/KeyError, or pyarrow's ArrowInvalid, on an unknown zone) and passing everything else up with ?, as each already does through out_of_range.

Comment thread pyo3/src/fetch.rs Resolved
Review feedback: resolving a timestamp column's zone now declines only when
pyarrow can't be imported or doesn't know or can't parse the zone (KeyError
from zoneinfo and pytz, ValueError), and propagates any other error.

Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
Co-authored-by: Isaac <no-reply@databricks.com>

@oss-reviewer-bot oss-reviewer-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: 2 Low

Looks good: I found two low-severity issues and nothing that changes behaviour. The batch hand-off between fetch_all_rows and the Arrow fetches handles every path I traced: declines, failed drains and repeat calls. Nit: the _handles helper in tests/test_rows.py never closes the Statement objects it creates.

Comment thread pyo3/src/rows.rs Resolved
Comment thread pyo3/src/fetch.rs Resolved
Review feedback: a zoned timestamp column looked its zone up again for
every batch; the converter now keeps the zones it resolved. The docstring
says that only such a column uses pyarrow, and the hand-off tests close the
Statements they create.

Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
Co-authored-by: Isaac <no-reply@databricks.com>

@oss-reviewer-bot oss-reviewer-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: 3 Low

Looks good: I found three low-severity issues and no correctness bugs in the new hand-off between fetch_all_rows and the Arrow fetches. The pending handling, decline paths and SchemaKey hash/equality look consistent, and the parity tests against pyarrow cover them well.

Comment thread pyo3/src/statement.rs Resolved
Comment thread pyo3/src/statement.rs Resolved
Comment thread pyo3/src/fetch.rs Resolved
…egative max_rows

Review feedback: fetch_all_arrow now reads through the pending queue (fill
to the end), so a failed read keeps the batches it had already read for the
next fetch instead of dropping them; the now-unused drain helpers are
removed. fetch_all_rows takes max_rows as an int and raises KernelError
(InvalidArgument) for a negative one instead of a PyO3 OverflowError.

Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
Co-authored-by: Isaac <no-reply@databricks.com>

@oss-reviewer-bot oss-reviewer-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No issues identified by the review bot.

This branch was previously deployed

1 inactive deployment
azure-prod — 5e59fbdb Deployed Nov 14, 2026 by oss-reviewer-bot[bot] via followup #3118
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant