From abaf90a56710dd721a747ddca3859c987fb5fa79 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 18:45:59 +0000 Subject: [PATCH 1/3] perf(python): share one tokio runtime across sessions Every pyo3 Session built its own multi-thread runtime with a worker per CPU, so 200 sessions on 16 cores held 3,200 kernel threads. Sessions now share one process-wide runtime, rebuilt in a forked child. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/NEXT_CHANGELOG.md | 3 + pyo3/src/runtime.rs | 57 ++++++++++- pyo3/src/session.rs | 28 ++---- pyo3/tests/test_runtime.py | 201 +++++++++++++++++++++++++++++++++++++ 4 files changed, 265 insertions(+), 24 deletions(-) create mode 100644 pyo3/tests/test_runtime.py diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index e0881e54..50aa0fb2 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -14,6 +14,9 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Added ### Changed +- All sessions in a process share one tokio runtime instead of each + starting its own worker per CPU, so many concurrent sessions use far + fewer threads and less CPU per query. ### Updated diff --git a/pyo3/src/runtime.rs b/pyo3/src/runtime.rs index a443b7c2..b6f76e59 100644 --- a/pyo3/src/runtime.rs +++ b/pyo3/src/runtime.rs @@ -12,13 +12,46 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! `KernelRuntime` — the session-owned tokio runtime. +//! `KernelRuntime` — the tokio runtime that drives every session. use pyo3::prelude::*; use std::ops::Deref; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use std::time::Duration; -use tokio::runtime::Runtime; +use tokio::runtime::{Builder, Runtime}; + +/// The process-wide runtime, tagged with the pid that built it. +static SHARED: Mutex)>> = Mutex::new(None); + +/// Runtime shared by every `Session` in the process. +/// +/// One worker pool per process rather than per session: a per-session +/// multi-thread runtime starts a worker per CPU for each connection, so +/// 200 sessions on 16 cores held 3,200 kernel threads. The static keeps a +/// reference, so `release` never shuts this runtime down. +/// +/// Worker threads don't survive `fork()`, so a child process builds its +/// own runtime. The parent's is leaked rather than dropped, because +/// dropping it would wait on threads that don't exist in the child. +pub(crate) fn shared() -> std::io::Result> { + let pid = std::process::id(); + let mut slot = SHARED.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((owner, runtime)) = slot.as_ref() { + if *owner == pid { + return Ok(runtime.clone()); + } + } + let runtime = Arc::new(KernelRuntime::new( + Builder::new_multi_thread() + .enable_all() + .thread_name("dbx-sql-kernel") + .build()?, + )); + if let Some((_, inherited)) = slot.replace((pid, runtime.clone())) { + std::mem::forget(inherited); + } + Ok(runtime) +} /// Upper bound on how long an explicit `close()` waits for the runtime to /// stop. Shutdown also waits on blocking-pool work (e.g. the OAuth refresh @@ -45,7 +78,8 @@ impl KernelRuntime { /// Release a handle at the end of an explicit `close()`. If it was the /// last one, shut down and wait for the workers with the GIL released, - /// so none is still logging into Python after `close()` returns. + /// so none is still logging into Python after `close()` returns. The + /// [`shared`] runtime is never the last one. pub(crate) fn release(runtime: Arc, py: Python<'_>) { if let Ok(mut runtime) = Arc::try_unwrap(runtime) { if let Some(runtime) = runtime.0.take() { @@ -139,4 +173,19 @@ mod tests { "release() returned before the worker finished" ); } + + #[test] + fn shared_runtime_is_reused_and_survives_release() { + let still_running = run_attached( + |py| { + let first = super::shared().expect("shared runtime"); + let second = super::shared().expect("shared runtime"); + assert!(Arc::ptr_eq(&first, &second)); + KernelRuntime::release(first, py); + py.detach(|| second.block_on(async { 7 })) == 7 + }, + "release() of the shared runtime", + ); + assert!(still_running, "shared runtime stopped after release()"); + } } diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index c626ee89..6be2115d 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -14,11 +14,11 @@ //! `Session` — Python class wrapping the kernel's `Session`. //! -//! Owns a multi-thread tokio runtime per session (one tokio worker -//! pool drives all I/O for this session). The runtime handle is -//! cloned into child `Statement` / `ExecutedStatement` objects so -//! they `block_on` the same pool without keeping the `Session` -//! pyclass alive longer than the user keeps a reference. +//! Sessions share one process-wide multi-thread tokio runtime (see +//! `runtime::shared`). The runtime handle is cloned into child +//! `Statement` / `ExecutedStatement` objects so they `block_on` the +//! same pool without keeping the `Session` pyclass alive longer than +//! the user keeps a reference. use crate::auth::{build_auth_config, OAuthParams}; use crate::executed_async::ExecutedAsyncStatement; @@ -29,7 +29,6 @@ use databricks_sql_kernel::{GeospatialResultRepresentation, Session as KSession} use pyo3::prelude::*; use std::collections::HashMap; use std::sync::Arc; -use tokio::runtime::Builder; /// Python-facing session handle. /// @@ -603,20 +602,9 @@ impl Session { None }; - // One tokio runtime per session. Multi-thread so CloudFetch - // chunk downloads can overlap with the main poll loop. Worker - // count left to tokio's default (logical CPU count). - let runtime = Arc::new(KernelRuntime::new( - Builder::new_multi_thread() - .enable_all() - .thread_name("dbx-sql-kernel") - .build() - .map_err(|e| { - pyo3::exceptions::PyRuntimeError::new_err(format!( - "failed to build tokio runtime: {e}" - )) - })?, - )); + let runtime = crate::runtime::shared().map_err(|e| { + pyo3::exceptions::PyRuntimeError::new_err(format!("failed to build tokio runtime: {e}")) + })?; // `Session::open` is async and grabs the current tokio handle. // Drive it on the runtime; the macro detaches the GIL for the diff --git a/pyo3/tests/test_runtime.py b/pyo3/tests/test_runtime.py new file mode 100644 index 00000000..5caa4a5f --- /dev/null +++ b/pyo3/tests/test_runtime.py @@ -0,0 +1,201 @@ +# Copyright (c) 2026 Databricks, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Sessions share one process-wide tokio runtime (no network).""" + +from __future__ import annotations + +import base64 +import contextlib +import gc +import itertools +import json +import os +import sys +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import databricks_sql_kernel as k +import pyarrow as pa +import pytest + +SESSIONS = "/api/2.0/sql/warehouses/test-wh/sessions" + + +def _attachment(): + batch = pa.record_batch([pa.array([1, 2], type=pa.int64())], names=["n"]) + buffer = pa.BufferOutputStream() + with pa.ipc.new_stream(buffer, batch.schema) as writer: + writer.write_batch(batch) + return base64.b64encode(buffer.getvalue()).decode() + + +@contextlib.contextmanager +def _server(): + """Local SEA stand-in: unique session / statement ids, inline results. + Yields ``(port, requests)``; ``requests`` collects ``(method, path)``.""" + requests = [] + ids = itertools.count(1) + attachment = _attachment() + + class Handler(BaseHTTPRequestHandler): + def respond(self, body, headers=()): + requests.append((self.command, self.path)) + self.rfile.read(int(self.headers.get("Content-Length", 0))) + payload = json.dumps(body).encode() + self.send_response(200) + self.send_header("Content-Length", str(len(payload))) + for name, value in headers: + self.send_header(name, value) + self.end_headers() + self.wfile.write(payload) + + def do_POST(self): + if self.path == SESSIONS: + self.respond({"session_id": f"s{next(ids)}"}, [("x-databricks-rt-session", "true")]) + return + self.respond( + { + "statement_id": f"q{next(ids)}", + "status": {"state": "SUCCEEDED"}, + "manifest": { + "format": "ARROW_STREAM", + "schema": { + "column_count": 1, + "columns": [ + {"name": "n", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0} + ], + }, + "total_chunk_count": 1, + "total_row_count": 2, + }, + "result": {"chunk_index": 0, "row_offset": 0, "row_count": 2, "attachment": attachment}, + } + ) + + def do_DELETE(self): + self.respond({}) + + def log_message(self, *_args): + pass + + with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + yield server.server_port, requests + finally: + server.shutdown() + + +def _session(port): + return k.Session( + host=f"http://127.0.0.1:{port}", + http_path="/sql/1.0/warehouses/test-wh", + access_token="test-token", + telemetry_enabled=False, + ) + + +def _query(session): + stmt = session.statement() + stmt.set_sql("SELECT 1") + executed = stmt.execute() + rows = 0 + while (batch := executed.fetch_next_batch()) is not None: + rows += batch.num_rows + executed.close() + stmt.close() + return rows + + +def _wait_for(predicate, timeout_s=5.0): + deadline = time.monotonic() + timeout_s + while not predicate(): + if time.monotonic() > deadline: + return False + time.sleep(0.02) + return True + + +@pytest.mark.skipif(not os.path.isdir("/proc/self/task"), reason="counts threads via /proc") +def test_sessions_do_not_add_runtime_threads(): + with _server() as (port, _): + first = _session(port) + baseline = len(os.listdir("/proc/self/task")) + others = [_session(port) for _ in range(8)] + try: + # A runtime per session added a worker per CPU for each one. + assert len(os.listdir("/proc/self/task")) < baseline + len(others) + finally: + for session in [first, *others]: + session.close() + + +def test_cleanup_of_closed_and_dropped_sessions_completes(): + with _server() as (port, requests): + keep = _session(port) + closed = _session(port) + assert _query(closed) == 2 + closed.close() + dropped = _session(port) + assert _query(dropped) == 2 + dropped_path = f"{SESSIONS}/{dropped.session_id}" + # Drop fires DeleteSession in the background on the shared runtime. + del dropped + gc.collect() + assert _query(keep) == 2 + + def deletes(): + return [path for method, path in requests if method == "DELETE"] + + def session_deletes(): + return [path for path in deletes() if "/statements/" not in path] + + assert _wait_for(lambda: len(deletes()) - len(session_deletes()) == 3) + assert _wait_for(lambda: dropped_path in session_deletes()) + keep.close() + assert len(session_deletes()) == 3 + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="needs fork()") +def test_forked_child_opens_sessions(): + with _server() as (port, _): + parent = _session(port) + assert _query(parent) == 2 + pid = os.fork() + if pid == 0: + # The parent's workers don't exist here; the child needs its own runtime. + code = 1 + try: + child = _session(port) + if _query(child) == 2: + code = 0 + child.close() + finally: + sys.stdout.flush() + os._exit(code) + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + done, status = os.waitpid(pid, os.WNOHANG) + if done: + assert os.waitstatus_to_exitcode(status) == 0 + break + time.sleep(0.05) + else: + os.kill(pid, 9) + os.waitpid(pid, 0) + pytest.fail("query hung in the forked child") + assert _query(parent) == 2 + parent.close() From 4d5f292d65f2a04d9e6af4f22ec2c9b91d47f1b2 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 20:10:01 +0000 Subject: [PATCH 2/3] fix(python): build the shared runtime without holding its lock Building the runtime spawns every worker, and a fork() taken while the lock is held would leave it locked forever in the child. The lock now covers only the pid check and the install; a runtime built by a thread that lost the race is dropped after the lock is released. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/runtime.rs | 38 ++++++++++++++++++++++++++++---------- pyo3/tests/test_runtime.py | 15 +++++++++------ 2 files changed, 37 insertions(+), 16 deletions(-) diff --git a/pyo3/src/runtime.rs b/pyo3/src/runtime.rs index b6f76e59..42f5cec0 100644 --- a/pyo3/src/runtime.rs +++ b/pyo3/src/runtime.rs @@ -16,12 +16,24 @@ use pyo3::prelude::*; use std::ops::Deref; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, MutexGuard}; use std::time::Duration; use tokio::runtime::{Builder, Runtime}; +type Slot = Option<(u32, Arc)>; + /// The process-wide runtime, tagged with the pid that built it. -static SHARED: Mutex)>> = Mutex::new(None); +static SHARED: Mutex = Mutex::new(None); + +fn lock_slot() -> MutexGuard<'static, Slot> { + SHARED.lock().unwrap_or_else(|e| e.into_inner()) +} + +fn installed(slot: &Slot, pid: u32) -> Option> { + slot.as_ref() + .filter(|(owner, _)| *owner == pid) + .map(|(_, runtime)| runtime.clone()) +} /// Runtime shared by every `Session` in the process. /// @@ -33,24 +45,30 @@ static SHARED: Mutex)>> = Mutex::new(None); /// Worker threads don't survive `fork()`, so a child process builds its /// own runtime. The parent's is leaked rather than dropped, because /// dropping it would wait on threads that don't exist in the child. +/// +/// The lock is never held while building: a `fork()` taken while it is +/// held would leave it locked forever in the child. pub(crate) fn shared() -> std::io::Result> { let pid = std::process::id(); - let mut slot = SHARED.lock().unwrap_or_else(|e| e.into_inner()); - if let Some((owner, runtime)) = slot.as_ref() { - if *owner == pid { - return Ok(runtime.clone()); - } + if let Some(runtime) = installed(&lock_slot(), pid) { + return Ok(runtime); } - let runtime = Arc::new(KernelRuntime::new( + let built = Arc::new(KernelRuntime::new( Builder::new_multi_thread() .enable_all() .thread_name("dbx-sql-kernel") .build()?, )); - if let Some((_, inherited)) = slot.replace((pid, runtime.clone())) { + let mut slot = lock_slot(); + // Another thread may have installed one meanwhile; ours, still idle, + // is dropped after the lock is released. + if let Some(runtime) = installed(&slot, pid) { + return Ok(runtime); + } + if let Some((_, inherited)) = slot.replace((pid, built.clone())) { std::mem::forget(inherited); } - Ok(runtime) + Ok(built) } /// Upper bound on how long an explicit `close()` waits for the runtime to diff --git a/pyo3/tests/test_runtime.py b/pyo3/tests/test_runtime.py index 5caa4a5f..f55f9068 100644 --- a/pyo3/tests/test_runtime.py +++ b/pyo3/tests/test_runtime.py @@ -55,12 +55,15 @@ def respond(self, body, headers=()): requests.append((self.command, self.path)) self.rfile.read(int(self.headers.get("Content-Length", 0))) payload = json.dumps(body).encode() - self.send_response(200) - self.send_header("Content-Length", str(len(payload))) - for name, value in headers: - self.send_header(name, value) - self.end_headers() - self.wfile.write(payload) + try: + self.send_response(200) + self.send_header("Content-Length", str(len(payload))) + for name, value in headers: + self.send_header(name, value) + self.end_headers() + self.wfile.write(payload) + except (BrokenPipeError, ConnectionResetError): + pass # The client went away (e.g. a pooled connection was dropped). def do_POST(self): if self.path == SESSIONS: From a1d14fda0e069cc78f2abfa80c7ee2de33e1a64f Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 20:46:29 +0000 Subject: [PATCH 3/3] docs(python): describe what close() guarantees on the shared runtime release() never stops the shared runtime, so work a closed session queued can still run after close() returns. Say so in the KernelRuntime and release docs, and narrow the fork note on the slot lock to what holds: Python forks hold the GIL, which every critical section also holds. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/lib.rs | 2 +- pyo3/src/runtime.rs | 25 ++++++++++++++++--------- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index f42ffa85..3a3d1d65 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -24,7 +24,7 @@ //! `maturin develop` / `maturin build`. //! //! The kernel's API is async — every method call from Python detaches -//! the GIL and `block_on`s on the session-owned tokio runtime. +//! the GIL and `block_on`s on the tokio runtime all sessions share. // `macros` is `#[macro_use]` so the `run_kernel!` / `alive!` / // `alive_mut!` macros are visible across the rest of the crate diff --git a/pyo3/src/runtime.rs b/pyo3/src/runtime.rs index 42f5cec0..4a5724e9 100644 --- a/pyo3/src/runtime.rs +++ b/pyo3/src/runtime.rs @@ -46,8 +46,11 @@ fn installed(slot: &Slot, pid: u32) -> Option> { /// own runtime. The parent's is leaked rather than dropped, because /// dropping it would wait on threads that don't exist in the child. /// -/// The lock is never held while building: a `fork()` taken while it is -/// held would leave it locked forever in the child. +/// A `fork()` taken while the slot lock is held would leave it locked in the +/// child. The lock is not held while building, and the only caller, +/// `Session.__new__`, holds the GIL across each short critical section, so a +/// fork from Python (`os.fork()` runs with the GIL held) can't observe it +/// locked. Native code that forks without the GIL could. pub(crate) fn shared() -> std::io::Result> { let pid = std::process::id(); if let Some(runtime) = installed(&lock_slot(), pid) { @@ -80,10 +83,14 @@ const CLOSE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(1); /// /// A plain `Runtime` drop blocks until every worker exits, but a worker /// forwarding a log record through `pyo3_log` waits for the GIL, so -/// dropping it with the GIL held deadlocks. Explicit `close()` calls go -/// through [`release`](Self::release), which waits with the GIL released. -/// `Drop` — reached when Python frees a handle — uses `shutdown_background`, -/// so workers may still run briefly after it returns. +/// dropping it with the GIL held deadlocks. [`release`](Self::release) +/// shuts a standalone runtime down with the GIL released; `Drop` uses +/// `shutdown_background`, so workers may still run briefly after it returns. +/// +/// Sessions use the [`shared`] runtime, which neither ever stops. Work a +/// closed session queued (fire-and-forget CloseStatement / DeleteSession, +/// telemetry, log records) can still run after its `close()` returns; the +/// logging bridge drops records once interpreter exit begins. /// /// Handle structs must declare their kernel object before this field: /// fields drop in order, and kernel `Drop` impls queue cleanup on it. @@ -95,9 +102,9 @@ impl KernelRuntime { } /// Release a handle at the end of an explicit `close()`. If it was the - /// last one, shut down and wait for the workers with the GIL released, - /// so none is still logging into Python after `close()` returns. The - /// [`shared`] runtime is never the last one. + /// last one, shut down and wait for the workers with the GIL released. + /// The [`shared`] runtime is never the last one, so for sessions this + /// only drops the handle. pub(crate) fn release(runtime: Arc, py: Python<'_>) { if let Ok(mut runtime) = Arc::try_unwrap(runtime) { if let Some(runtime) = runtime.0.take() {