Skip to content

perf(python): skip GIL hand-offs that wait for nothing - #458

Closed
vuanhphung wants to merge 5 commits into
mainfrom
perf/rd-gil-handoffs
Closed

vuanhphung wants to merge 5 commits into
mainfrom
perf/rd-gil-handoffs

Conversation

@vuanhphung

@vuanhphung vuanhphung commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Under many Python threads, each py.detach in 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-blocking try_next_batch() first and releases the GIL only when the batch isn't ready (a CloudFetch chunk still downloading). Both paths drive the ExecutedStatement, so auto-close-on-drain is unchanged. The fast path is taken only when the new ExecutedStatement::try_next_batch_is_cheap() says a ready read is a buffer hand-off. Readers opt in (default false). 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:

Local TLS mock, 50 ms server time, 4 × 200 sessions, 6 client cores main this PR
avg QPS 3,452 / 3,500 3,658 / 3,699 (+6%)
peak QPS 4,132 / 4,081 4,289 / 4,258 (+4%)
steady QPS 3,790 / 3,861 4,077 / 4,152 (+7%)
query p50 203 / 201 ms 192 / 190 ms
Live Reyden warehouse, 1 × 200 sessions, 8 cores, 3 runs (run 1 under heavy shared load) main this PR
avg QPS 110 / 489 / 484 545 / 509 / 446
peak QPS 209 / 844 / 827 795 / 780 / 837
query p50 1,225 / 239 / 236 ms 247 / 233 / 240 ms
failed queries (server errors) 242 / 521 / 555 472 / 481 / 436
client CPU 18.9 / 54.4 / 57.6 s 48.2 / 47.1 / 50.1 s

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 (the Pending fallback), and a rewritten column each return the rows, end the stream, and send exactly one CloseStatement across drain plus explicit close(); a main-thread execute() still raises KeyboardInterrupt within 2 s of SIGINT. Rust unit tests cover the poll-first helper (ready and pending futures) and try_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) and cargo test --lib pass. cargo +stable fmt, cargo clippy --all-targets -- -D warnings and cargo test in pyo3/ 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):

kernel main this PR
Average QPS (setup included) 2024 (1957-2217) 2102 (1892-2104)
Steady QPS (after all sessions open) 2062 (1994-2261) 2140 (1928-2144)
Query latency p50 (ms) 372 (340-384) 358 (356-395)
Client CPU per query (ms) 1.39 (1.30-1.46) 1.17 (1.12-1.17)
Session open p50, from process start (s) 2.21 (2.09-2.22) 2.04 (2.03-2.08)

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):

kernel main this PR
Average QPS (setup included) 6158 (6135-6181) 6093 (6064-6122)
Peak QPS (best second) 6572 (6555-6590) 6548 (6523-6574)
Query latency p50 (ms) 123 (123-123) 123 (122-124)
Client CPU per query (ms) 1.33 (1.32-1.34) 1.27 (1.26-1.28)

Average QPS change per round: -1.2%, -1.0%.

This pull request and its description were written by Isaac.

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>

@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. 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 / End fast paths with an inline result. Nothing exercises the Pending → run_sync_kernel!(fetch::next_batch_exec) fallback, or the run_ready_first Pending branch in close() from Python. The fallback is the path that matters for CloudFetch correctness: no batch skipped or duplicated after a Pending, and auto-close still fires exactly once. A Rust unit test with a reader that returns Pending and then Ready would cover it: drive it through the same match and assert the batch sequence plus a single CloseStatement.

Comment thread pyo3/src/statement.rs Resolved
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>
@vuanhphung

Copy link
Copy Markdown
Collaborator Author

On the two review-body notes:

  • Pending fallback untested: covered in f53c150. test_worker_thread_fetch_closes_statement_once is now parametrized over an inline result, a CloudFetch external link whose chunk is served 300 ms late (the first read is Pending and falls back to the blocking path), and a rewritten column. Each case asserts the exact rows, two Nones after the end, and exactly one CloseStatement across drain plus explicit close(). All cases also pass on main, so the behaviour is unchanged.
  • Caching the main-thread ident: I'd keep the lookup per call. After os.fork() from a non-main thread, the child's main thread is the forking thread (threading re-points main_thread() after fork), so an ident cached in the parent would stop signal checks in the child's real main thread and Ctrl-C would no longer interrupt execute() there. The two attribute calls cost well under a microsecond against an execute() that makes at least one HTTP round trip.

@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

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.

Comment thread pyo3/src/statement.rs Resolved
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>

@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

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).

Comment thread pyo3/src/gil.rs Resolved
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>

@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.

@vuanhphung

Copy link
Copy Markdown
Collaborator Author

Close in favor of #477

@vuanhphung vuanhphung closed this Nov 18, 2026

This branch was previously deployed

1 inactive deployment
azure-prod — a9d5ab99 Deployed Nov 13, 2026 by oss-reviewer-bot[bot] via followup #2912
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