Skip to content
Merged
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
69 changes: 9 additions & 60 deletions src/c_abi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,34 +81,10 @@ pub type KernelLogCallback = unsafe extern "C" fn(
/// process (matches the migration-plan §5.2 contract).
static RUNTIME: OnceLock<tokio::runtime::Runtime> = OnceLock::new();

// Tokio normally gives runtime workers a 2 MiB stack, but without an explicit
// override its thread builder honours the embedding process's RUST_MIN_STACK.
// Native consumers may set that variable for their own thread pools; keep it
// from shrinking the kernel-owned workers below Tokio's supported default.
const C_ABI_RUNTIME_THREAD_STACK_SIZE: usize = 2 * 1024 * 1024;

/// Resolve the worker-thread stack size for the C-ABI runtime from the ambient
/// `RUST_MIN_STACK` value (parsed to `Some(bytes)`, or `None` when unset or
/// unparseable).
///
/// [`C_ABI_RUNTIME_THREAD_STACK_SIZE`] (2 MiB) is a **floor, not a cap**: a
/// too-small ambient `RUST_MIN_STACK` is clamped up to the floor (preserving
/// databricks/databricks-sql-kernel#326), while a host that deliberately asked
/// for *more* than 2 MiB keeps its larger stack rather than being silently
/// shrunk.
fn c_abi_runtime_thread_stack_size(ambient_rust_min_stack: Option<usize>) -> usize {
ambient_rust_min_stack
.unwrap_or(0)
.max(C_ABI_RUNTIME_THREAD_STACK_SIZE)
}

/// Read and parse the ambient `RUST_MIN_STACK` env var into `Some(bytes)`, or
/// `None` when it is unset or not a valid `usize`.
fn ambient_rust_min_stack() -> Option<usize> {
std::env::var("RUST_MIN_STACK")
.ok()
.and_then(|v| v.parse::<usize>().ok())
}
// The kernel-owned worker stack floor lives in `crate::util::runtime` as a
// single source of truth shared with the telemetry runtime; see that module
// for the floor-not-cap semantics and the #326 / #328 history.
use crate::util::runtime::{ambient_rust_min_stack, runtime_thread_stack_size};

/// Fetch (initialising on first use) the process-wide C-ABI runtime.
///
Expand All @@ -130,7 +106,7 @@ pub(crate) fn runtime() -> crate::kernel_error::Result<&'static tokio::runtime::
let built = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.thread_name("kernel-c-abi")
.thread_stack_size(c_abi_runtime_thread_stack_size(ambient_rust_min_stack()))
.thread_stack_size(runtime_thread_stack_size(ambient_rust_min_stack()))
.build()
.map_err(|e| {
crate::kernel_error::Error::internal()
Expand Down Expand Up @@ -461,37 +437,10 @@ mod tests {

const SMALL_STACK_CHILD: &str = "DATABRICKS_KERNEL_SMALL_STACK_CHILD";

/// Floor-not-cap (the bug in #328): when the ambient `RUST_MIN_STACK` is
/// LARGER than the 2 MiB floor, the resolved worker stack size must
/// preserve the larger value rather than shrinking workers to 2 MiB. The
/// databricks-odbc partner runs with `RUST_MIN_STACK=3194880` and must not
/// have its C-ABI workers silently reduced.
#[test]
fn c_abi_runtime_stack_size_preserves_larger_rust_min_stack() {
let ambient = 3_194_880; // ulimit -s 3120 * 1024, the partner's value
assert!(ambient > C_ABI_RUNTIME_THREAD_STACK_SIZE);
assert_eq!(
c_abi_runtime_thread_stack_size(Some(ambient)),
ambient,
"a RUST_MIN_STACK larger than the 2 MiB floor must be preserved, not shrunk"
);
}

/// Floor preserved (the #326 behavior the fix must keep): a too-small or
/// unset ambient `RUST_MIN_STACK` is clamped UP to the 2 MiB floor.
#[test]
fn c_abi_runtime_stack_size_clamps_small_rust_min_stack_up_to_floor() {
assert_eq!(
c_abi_runtime_thread_stack_size(Some(16_384)),
C_ABI_RUNTIME_THREAD_STACK_SIZE,
"a RUST_MIN_STACK below the floor must clamp up to 2 MiB"
);
assert_eq!(
c_abi_runtime_thread_stack_size(None),
C_ABI_RUNTIME_THREAD_STACK_SIZE,
"an unset RUST_MIN_STACK must default to the 2 MiB floor"
);
}
// The pure floor-not-cap resolution (#326 / #328) is exercised once over
// the shared helper in `crate::util::runtime`. Here we keep only the
// subprocess probe that verifies the C-ABI runtime is actually built with
// that floor under an ambient RUST_MIN_STACK.

/// The C ABI owns its runtime, so an embedding process's `RUST_MIN_STACK`
/// setting must not be able to shrink the runtime workers below Tokio's
Expand Down
78 changes: 70 additions & 8 deletions src/telemetry/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use super::models::TelemetryFrontendLog;
use crate::config::TelemetryConfig;
use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use tokio::runtime::Handle;
use tokio::runtime::{Handle, Runtime};

const STATE_ACTIVE: u8 = 0;
const STATE_CLOSING: u8 = 1;
Expand All @@ -37,11 +37,21 @@ pub(super) struct TelemetryClient {
}

impl TelemetryClient {
pub(super) fn new(config: &TelemetryConfig, exporter: Arc<dyn TelemetryExporter>) -> Arc<Self> {
pub(super) fn new(
config: &TelemetryConfig,
exporter: Arc<dyn TelemetryExporter>,
) -> Option<Arc<Self>> {
assert!(
!config.flush_interval.is_zero(),
"TelemetryClient requires a non-zero flush interval; TelemetryRuntime should filter invalid configs"
);
let runtime_handle = match telemetry_runtime_handle() {
Ok(handle) => handle,
Err(error) => {
tracing::debug!(%error, "failed to create telemetry runtime; disabling telemetry");
return None;
}
};
let client = Arc::new(Self {
exporter,
batch_size: config.batch_size,
Expand All @@ -52,10 +62,10 @@ impl TelemetryClient {
flush_lock: tokio::sync::Mutex::new(()),
state: AtomicU8::new(STATE_ACTIVE),
timer: Mutex::new(None),
runtime_handle: Handle::current(),
runtime_handle,
});
client.start_timer();
client
Some(client)
}

pub(super) fn enqueue(self: &Arc<Self>, log: TelemetryFrontendLog) {
Expand Down Expand Up @@ -86,6 +96,20 @@ impl TelemetryClient {
let _ = tokio::time::timeout(timeout, self.flush_once_wait()).await;
}

pub(super) fn schedule_flush_bounded(self: &Arc<Self>) -> tokio::task::JoinHandle<()> {
let client = Arc::clone(self);
self.runtime_handle.spawn(async move {
client.flush_bounded().await;
})
}

pub(super) fn schedule_close(self: &Arc<Self>) -> tokio::task::JoinHandle<()> {
let client = Arc::clone(self);
self.runtime_handle.spawn(async move {
client.close().await;
})
}

pub(super) async fn close(self: &Arc<Self>) {
if self
.state
Expand Down Expand Up @@ -158,13 +182,47 @@ impl TelemetryClient {
}
}

// A real HTTP telemetry export needs more than a tiny stack: a host running
// with e.g. RUST_MIN_STACK=16384 would otherwise overflow the worker stack and
// abort the process. The worker stack floor is shared with the C-ABI runtime
// via `crate::util::runtime` (single source of truth); see that module for the
// floor-not-cap semantics and the #326 / #328 history.
use crate::util::runtime::{ambient_rust_min_stack, runtime_thread_stack_size};

fn telemetry_runtime_handle() -> std::io::Result<Handle> {
// A host client can outlive the session that created it. Keep its timer,
// batch tasks, and Drop cleanup independent of any session-owned runtime.
//
// Only a successfully-built runtime is cached. A build failure is NOT
// memoized, so a transient failure (e.g. the OS momentarily can't spawn
// the worker thread under resource pressure) is retried on the next
// session rather than poisoning telemetry for the rest of the process.
static RUNTIME: Mutex<Option<Runtime>> = Mutex::new(None);
let mut runtime = RUNTIME.lock().expect("poisoned telemetry runtime");
if let Some(runtime) = runtime.as_ref() {
return Ok(runtime.handle().clone());
}
let built = tokio::runtime::Builder::new_multi_thread()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new runtime omits thread_stack_size, so its worker inherits RUST_MIN_STACK. With RUST_MIN_STACK=16384, a real HTTP telemetry export causes stack overflow in dbx-sql-telemetry and aborts the process. The C ABI runtime already guards against this. Apply the same 2 MiB minimum here, preserving larger configured values.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both clean. The fix is complete and verified.

Pushed b205bd5.

.worker_threads(1)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low — Exports now always run on the dedicated dbx-sql-telemetry runtime, but they still go through the creating session's pooled reqwest::Client. The cached per-host client keeps that first exporter even after the creating session has closed. Hyper's connection-driver tasks run on whichever runtime opened the connection. So one pool now holds connections driven by the session runtime (query traffic) next to connections driven by the telemetry runtime, and telemetry and queries hit the same host. Once a session-owned runtime shuts down (the timer_survives_creator_session_runtime_shutdown scenario), a telemetry export can check out a pooled connection whose driver task is gone. That is the known reqwest/hyper "dispatch task is gone" failure. A batch that fails this way is silently dropped, and repeated failures can trip the circuit breaker. I couldn't confirm the failure end to end. Two possible fixes: give the telemetry exporter its own HTTP client built on the telemetry runtime, or add a test where the creator runtime has made a real pooled request before it is dropped.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied the fix locally but the push failed (likely another commit landed on this branch since I started). This bundle covered 1 thread(s); all reverted. Re-trigger by replying to this thread.

[push retry after rebase failed]
 - A pull request for this branch has been added to a merge queue. Branches that        
remote:   are queued for merging cannot be updated. To modify this branch, dequeue the        
remote:   associated pull request.        
To https://github.com/databricks/databricks-sql-kernel.git
 ! [remote rejected] jay/telemetry-flush-last-client -> jay/telemetry-flush-last-client (protected branch hook declined)
error: failed to push some refs to 'https://github.com/databricks/databricks-sql-kernel.git'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for trying the fix. The push was rejected because the PR is in the merge queue, so nothing on the branch has changed, and the current code still sends exports through the creating session's pooled client. The finding is still open. Someone will need to apply the change by hand, either after taking the PR out of the queue or in a follow-up PR. The change is to give the telemetry exporter its own HTTP client built on the dbx-sql-telemetry runtime, or to add a test where the creator runtime makes a real pooled request before it's dropped.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⛔ NEEDS HUMAN DECISION — the bots can't resolve this thread; a maintainer's input is required.

I agree with the finding: telemetry exports should not share the creating session's pooled reqwest::Client, whose connections can be driven by a session runtime that has since shut down. But I can't apply the fix in this PR. The branch is in the merge queue, and the earlier push was rejected with "Branches that are queued for merging cannot be updated". A human needs to either take the PR out of the queue and re-trigger me, or make the change in a follow-up PR. The change is to give the telemetry exporter its own HTTP client built on the dbx-sql-telemetry runtime, plus an offline wiremock test where the creator runtime makes a real pooled request before it is dropped and a later export still succeeds.

.thread_name("dbx-sql-telemetry")
.thread_stack_size(runtime_thread_stack_size(ambient_rust_min_stack()))
.enable_all()
.build()?;
let handle = built.handle().clone();
*runtime = Some(built);
Ok(handle)
}

#[cfg(test)]
mod tests {
use super::*;
use crate::telemetry::test_support::CapturingTelemetryExporter;
use crate::telemetry::TelemetryRequest;
use std::time::Duration;

// The pure floor-not-cap resolution (#326 / #328) is exercised once over
// the shared helper in `crate::util::runtime`.

#[tokio::test]
async fn batch_size_triggers_background_flush() {
let exporter = CapturingTelemetryExporter::default();
Expand All @@ -174,7 +232,8 @@ mod tests {
flush_interval: Duration::from_secs(60),
..TelemetryConfig::default()
};
let client = TelemetryClient::new(&config, Arc::new(exporter.clone()));
let client = TelemetryClient::new(&config, Arc::new(exporter.clone()))
.expect("telemetry runtime should start");

client.enqueue(sample_log("one"));
assert!(exporter.requests().is_empty());
Expand Down Expand Up @@ -204,7 +263,8 @@ mod tests {
flush_interval: Duration::from_secs(60),
..TelemetryConfig::default()
};
let client = TelemetryClient::new(&config, Arc::new(exporter.clone()));
let client = TelemetryClient::new(&config, Arc::new(exporter.clone()))
.expect("telemetry runtime should start");

let worker_client = Arc::clone(&client);
std::thread::spawn(move || {
Expand Down Expand Up @@ -237,7 +297,8 @@ mod tests {
flush_interval: Duration::from_millis(20),
..TelemetryConfig::default()
};
let client = TelemetryClient::new(&config, Arc::new(exporter.clone()));
let client = TelemetryClient::new(&config, Arc::new(exporter.clone()))
.expect("telemetry runtime should start");

client.enqueue(sample_log("one"));

Expand Down Expand Up @@ -265,7 +326,8 @@ mod tests {
flush_interval: Duration::from_secs(60),
..TelemetryConfig::default()
};
let client = TelemetryClient::new(&config, Arc::new(exporter.clone()));
let client = TelemetryClient::new(&config, Arc::new(exporter.clone()))
.expect("telemetry runtime should start");

client.enqueue(sample_log("one"));
client.close().await;
Expand Down
Loading
Loading