Repository navigation
perf(python): skip GIL hand-offs that wait for nothing - #458
vuanhphung wants to merge 5 commits into
Conversation
With many Python threads, every py.detach costs a GIL release and a contended re-acquire. fetch_next_batch now takes batches that are already in memory through try_next_batch with the GIL held, close() of a drained statement completes without detaching, and execute() on a non-main thread runs in one GIL-released slice instead of waking every 100 ms for signal checks only the main thread can act on. 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. The kernel side checks out: ExecutedStatement::try_next_batch keeps auto-close-on-drain, and once the drain sets the closed flag, close() returns immediately without I/O, so polling it first while holding the GIL is safe. I found two low-severity issues: per-batch post-processing now runs while the GIL is held, and nothing tests the Pending fallback path. One nit: on_main_thread makes two Python calls on every execute(). Caching threading.main_thread().ident in the PyOnceLock would leave just one call.
Other findings
- ⚪ Nit — The new no-network test covers only the
TryNextBatch::Ready/Endfast paths with an inline result. Nothing exercises thePending→run_sync_kernel!(fetch::next_batch_exec)fallback, or therun_ready_firstPendingbranch inclose()from Python. The fallback is the path that matters for CloudFetch correctness: no batch skipped or duplicated after aPending, and auto-close still fires exactly once. A Rust unit test with a reader that returnsPendingand thenReadywould cover it: drive it through the same match and assert the batch sequence plus a single CloseStatement.
try_next_batch runs the post-processor's per-batch column rewrites (geospatial, interval, JSON, untyped NULL) on the calling thread, so fetch_next_batch now takes its GIL-held fast path only when the stream has no rewrites. Adds rewrites_batches() on ExecutedStatement and ResultStream, and tests for the CloudFetch Pending fallback and the rewritten-column path. Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> Co-authored-by: Isaac <no-reply@databricks.com>
|
On the two review-body notes:
|
There was a problem hiding this comment.
Verdict: 1 Low
The change is correct, with one low-severity robustness concern. When the GIL-held fast path ends the stream, it still auto-closes and sets exhausted. exhausted is only set after the stream has gone through exec.next_batch/try_next_batch, which already fired the close, so close() takes the short-circuit and the first poll in run_ready_first does no I/O. The non-main-thread path skips only signal checks, which never fire off the main thread anyway. Nit: the new pytest cases check rows and that exactly one CloseStatement is sent, but they would also pass if the GIL-held fast path were never taken, so the change in GIL behavior itself is untested.
Replace rewrites_batches() with try_next_batch_is_cheap(), a capability that defaults to false. The inline, CloudFetch, inline-streaming, in-memory and empty readers opt in, and the post-processor reports it only when it has no column rewrites. A reader that keeps the trait's default try_next_batch therefore stays on the blocking next_batch path instead of surfacing "reader does not support non-blocking batch reads" from fetch_next_batch. 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
Looks good, with one low-severity concern. I checked that the fast path still drives ExecutedStatement::try_next_batch, so auto-close-on-drain is unchanged. After a drain, close() sees closed=true and is ready on the first poll, so it does no I/O. The post-processor only opts in when nothing rewrites column values. The one finding is that the main-thread check can be fooled by monkey-patched threading (gevent).
Greenlet libraries (gevent, eventlet) patch threading.get_ident, so a greenlet on the main OS thread looked like a worker and execute() lost its Ctrl-C checks. Also accept a native_id match; ident alone stays the check after fork, which threading refreshes for ident but not for native_id. Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> Co-authored-by: Isaac <no-reply@databricks.com>
|
Close in favor of #477 |
Under many Python threads, each
py.detachin the binding costs a GIL release and a contended re-acquire. In a 200-thread profile of databricks-sql-connector (use_kernel=True) about 20% of client CPU samples were GIL futex waits and wakes, and a small query made four or more hand-offs even when three of them had nothing to wait for:ExecutedStatement.fetch_next_batch()released the GIL to read an inline batch that is already in memory, and again to learn the stream had ended.ExecutedStatement.close()released it after a full drain, when auto-close-on-drain had already sent CloseStatement and there is no I/O left.Statement.execute()re-acquired it every 100 ms to check for signals. Only Python's main thread runs signal handlers, so on every other thread the tick does nothing but hand the GIL back and forth.fetch_next_batch()now tries the kernel's non-blockingtry_next_batch()first and releases the GIL only when the batch isn't ready (a CloudFetch chunk still downloading). Both paths drive theExecutedStatement, so auto-close-on-drain is unchanged. The fast path is taken only when the newExecutedStatement::try_next_batch_is_cheap()says a ready read is a buffer hand-off. Readers opt in (defaultfalse). The inline, CloudFetch (chunks are decoded by their download tasks), inline-streaming, in-memory and empty readers do; results whose batches need column rewrites (geospatial, interval, JSON, untyped NULL) do not. So no per-row work moves under the GIL.close()of a drained statement polls the close future once with the GIL held and detaches only if it is not already complete.execute()keeps the 100 ms interruptible slices on the main thread and runs in one GIL-released slice elsewhere.Measurements. databricks-sql-connector
use_kernel=True, the C800 cold-start benchmark (each session runs a small query back to back). Main vs this PR, interleaved, 2 runs each:The live warehouse is the bottleneck at this load, so live QPS stays within noise. Client CPU per query drops ~13%.
With the connector's pending small-result conversion fix (databricks/databricks-sql-python#1048) applied, on the same mock 4 × 200 setup (6 client cores): main 7,684 / 7,621 avg QPS (peak 9,213 / 9,014), this PR 8,639 / 8,881 (+15%; peak 9,553 / 9,863), and 11,205 / 11,171 (+46%) together with #457. A separate run on 16 client cores with a 20 ms mock put this PR alone within noise and about +3.5% avg on top of #457; the gain shows mainly where client CPU is the limit.
Tests. New no-network tests in
pyo3/tests/test_sync_fetch.py: worker-thread execute and fetch over an inline result, a CloudFetch link whose chunk arrives late (thePendingfallback), and a rewritten column each return the rows, end the stream, and send exactly one CloseStatement across drain plus explicitclose(); a main-threadexecute()still raisesKeyboardInterruptwithin 2 s of SIGINT. Rust unit tests cover the poll-first helper (ready and pending futures) andtry_next_batch_is_cheap()for the post-processor cases (no transform, manifest-only re-project, column rewrite, inner reader not opted in). Root crate: fmt, clippy (both TLS backends) andcargo test --libpass.cargo +stable fmt,cargo clippy --all-targets -- -D warningsandcargo testinpyo3/pass; the pyo3 pytest suite passes except 7 live metadata and session-conf tests that fail identically on main against the test warehouse (CLOUD_FETCH_ERROR.OSD_URL_GEN, a server-side error).Live benchmark (staging Large Reyden warehouse)
TPC-H Q6 on a Large Real-Time warehouse, 800 sessions (4 processes x 200 threads), cold start, each session querying back to back for 120 s, 16 client cores. Isolated A/B: only this change vs connector main 0c1b9e80 + kernel main db23442, 3 interleaved rounds, nothing else on the warehouse. Measured at a9d5ab9. Median (min-max):
QPS within noise; client CPU per query ~15% lower.
SELECT 1 on an X-Large Real-Time warehouse (driver-bound). Q6 above is limited by the warehouse, so the same harness also ran
SELECT 1, where the client is the limit: X-Large warehouse, 4 processes x 200 threads, 120 s, 16 client cores, this change vs connector main 0c1b9e80 + kernel main db23442, measured at a9d5ab9, run in rotation with the other factory PRs, 2 rounds. Median (min-max):Average QPS change per round: -1.2%, -1.0%.
This pull request and its description were written by Isaac.