Repository navigation
perf(python): return small results as Python rows without pyarrow - #467
vuanhphung wants to merge 7 commits into
Conversation
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>
There was a problem hiding this comment.
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.
…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>
There was a problem hiding this comment.
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 theImportErrorwhen pyarrow is missing is deliberate. ButKeyboardInterrupt,MemoryError, or an unexpected bug insidestring_to_tzinfois 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 (ImportErroron the import;ValueError/KeyError, or pyarrow'sArrowInvalid, on an unknown zone) and passing everything else up with?, aseachalready does throughout_of_range.
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>
There was a problem hiding this comment.
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.
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>
There was a problem hiding this comment.
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.
…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>
For a small result, the Python connector spends more GIL-held time on handling the result than on anything else:
arrow_schema()and eachfetch_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 withSchema.equals(check_metadata=True)(C++ metadata fingerprints on every call), and then runsto_pylist()per column. A one-process client runningSELECT 1on 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
ExecutedStatementandResultStream: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'sto_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 ownstring_to_tzinfo). It returnsNonewhen more thanmax_rowsrows remain, a column has another type, a float is NaN (unlessnan_ok) or a value is outside Python'sdate/datetimerange;fetch_next_batch/fetch_all_arrowthen return the batches it already read.schema_key(): a hashableSchemaKeythat compares two results' schemas (names, types, nullability, metadata) in Rust, so callers can cache what they derive from a schema without building apyarrow.Schema._rows_from_arrowruns 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_rowsshould read in-memory batches with the GIL held asfetch_next_batchdoes there; that is one more commit (d58c5eb onperf/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_rowsreleases the GIL once to read the batch.Testing.
cargo test(new unit tests for the conversion, declines and the pending-batch hand-off), clippy, andtests/test_rows.py: every converted type againstto_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 forSELECT, 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 1query on one connection (perf hardware breakpoint onPyEval_SaveThread, local mock server; connector databricks/databricks-sql-python#1061):fetchallfetchoneLive:
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: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.