Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions pyo3/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion pyo3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
92 changes: 83 additions & 9 deletions pyo3/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,67 @@
// 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, MutexGuard};
use std::time::Duration;
use tokio::runtime::Runtime;
use tokio::runtime::{Builder, Runtime};

type Slot = Option<(u32, Arc<KernelRuntime>)>;

/// The process-wide runtime, tagged with the pid that built it.
static SHARED: Mutex<Slot> = 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<Arc<KernelRuntime>> {
slot.as_ref()
.filter(|(owner, _)| *owner == pid)
.map(|(_, runtime)| runtime.clone())
}

/// 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.
///
/// 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<Arc<KernelRuntime>> {
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
let pid = std::process::id();
if let Some(runtime) = installed(&lock_slot(), pid) {
return Ok(runtime);
}
let built = Arc::new(KernelRuntime::new(
Builder::new_multi_thread()
.enable_all()
.thread_name("dbx-sql-kernel")
.build()?,
));
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(built)
}

/// 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
Expand All @@ -29,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.
Expand All @@ -44,8 +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.
/// 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<Self>, py: Python<'_>) {
if let Ok(mut runtime) = Arc::try_unwrap(runtime) {
if let Some(runtime) = runtime.0.take() {
Expand Down Expand Up @@ -139,4 +198,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()");
}
}
28 changes: 8 additions & 20 deletions pyo3/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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.
///
Expand Down Expand Up @@ -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| {
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
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
Expand Down
204 changes: 204 additions & 0 deletions pyo3/tests/test_runtime.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
# 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()
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:
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()
Loading