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
17 changes: 14 additions & 3 deletions include/databricks_kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -577,9 +577,20 @@ KernelStatusCode kernel_session_is_open(const kernel_session_t* session, bool* o
* alive); on failure returns the mapped status (a transport/availability
* failure surfaces as Unavailable / NetworkError / Timeout — treat as
* "connection dead" when backing SQL_ATTR_CONNECTION_DEAD; the full error
* is in kernel_get_last_error). Runs SQL, so it MUST be called from a
* native (non-async-runtime) thread. No ownership. */
KernelStatusCode kernel_session_test(const kernel_session_t* session);
* is in kernel_get_last_error).
*
* `timeout_secs` bounds the WHOLE probe (every retry and HTTP round-trip
* included) to that many seconds; 0 means no per-call deadline (the probe
* runs on the session's own retry/timeout budget — the historical
* behaviour). This is the per-call deadline a host backs
* `ConnectionTestTimeout` with: with 0 the configured value has no effect.
* When the probe exceeds the deadline the call returns Timeout (typed error
* in kernel_get_last_error). The bound is scoped to this probe and cannot
* alter the timeout of later requests on the session.
*
* Runs SQL, so it MUST be called from a native (non-async-runtime) thread.
* No ownership. */
KernelStatusCode kernel_session_test(const kernel_session_t* session, uint64_t timeout_secs);

/* Construct a new mutable statement bound to this session. */
KernelStatusCode kernel_session_new_statement(kernel_session_t* session,
Expand Down
19 changes: 17 additions & 2 deletions src/c_abi/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1672,6 +1672,17 @@ pub unsafe extern "C" fn kernel_session_is_open(
/// `kernel_get_last_error`. Mirrors the reference / JDBC drivers'
/// connection-test probe.
///
/// `timeout_secs` bounds the WHOLE probe — every retry and HTTP round-trip
/// included — to that many seconds; `0` means no per-call deadline (the probe
/// runs on the session's own retry/timeout budget, the historical behaviour).
/// This is the per-call deadline a host backs `ConnectionTestTimeout` with
/// (odbc#347-C): without it `ConnectionTestTimeout=1` and `=30` behave
/// identically. When the probe exceeds the deadline the call returns
/// `KernelStatusCode::Timeout` (the typed error is in `kernel_get_last_error`);
/// a host may treat that as "connection dead" or surface it distinctly. The
/// bound is scoped to this probe and cannot alter the timeout of later requests
/// on the session.
///
/// Runs SQL, so — like the transaction-control entry points — it MUST be
/// invoked from a native (non-async-runtime) thread. Does not borrow
/// ownership; the caller still owns `session`.
Expand All @@ -1680,15 +1691,19 @@ pub unsafe extern "C" fn kernel_session_is_open(
/// `session` must be a live handle from [`kernel_session_open`] (not yet
/// closed via [`kernel_session_close`]).
#[no_mangle]
pub unsafe extern "C" fn kernel_session_test(session: *const kernel_session_t) -> KernelStatusCode {
pub unsafe extern "C" fn kernel_session_test(
session: *const kernel_session_t,
timeout_secs: u64,
) -> KernelStatusCode {
crate::c_abi::error::clear_error();
let Some(session) = (session as *const Session).as_ref() else {
crate::c_abi::error::store_error(
Error::invalid_argument().message("kernel_session_test: session must not be null"),
);
return KernelStatusCode::InvalidArgument;
};
match block_on_ffi(|| session.test_connection()) {
let deadline = (timeout_secs > 0).then(|| std::time::Duration::from_secs(timeout_secs));
match block_on_ffi(|| session.test_connection_with_timeout(deadline)) {
Ok(()) => KernelStatusCode::Success,
Err(code) => code,
}
Expand Down
37 changes: 37 additions & 0 deletions src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,43 @@ impl Session {
.await
}

/// Like [`test_connection`](Self::test_connection), but bounds the whole
/// probe — every retry and HTTP round-trip included — to `deadline`. This
/// is the per-call deadline a host backs `ConnectionTestTimeout` with
/// (odbc#347-C): without it the probe runs on the session's own
/// retry/timeout budget, so `ConnectionTestTimeout=1` and `=30` behave
/// identically and a `SQL_ATTR_CONNECTION_DEAD` read during an outage can
/// block for the session's unrelated retry budget rather than the
/// customer-selected duration.
///
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
/// A `None` deadline is exactly [`test_connection`] (no per-call bound).
/// When the probe does not complete within `deadline`, returns a
/// `Timeout`-category error (distinct wording so a host can tell "probe
/// deadline hit" from a transport failure) — the caller decides what
/// `SQL_ATTR_CONNECTION_DEAD` reports for that case. The bound is scoped to
/// this future only: it wraps the probe in `tokio::time::timeout`, so it
/// cannot alter the timeout of any other request on the session.
pub async fn test_connection_with_timeout(&self, deadline: Option<Duration>) -> Result<()> {
match deadline {
None => self.test_connection().await,
Some(d) => match tokio::time::timeout(d, self.test_connection()).await {
Ok(result) => result,
// Build via the categorised `Error::timeout()` constructor (repo
// convention), but mark it non-retryable: unlike a transport
// timeout, this deadline was deliberately set by the caller
// (e.g. ConnectionTestTimeout), so re-running the probe would
// just hit the same bound again. Retrying is the caller's
// decision, not something a retry wrapper should do implicitly.
Err(_elapsed) => Err(Error::timeout()
.message(format!(
"connection test did not complete within {} second(s)",
d.as_secs()
))
.with_retryable(false)),
},
}
}

/// Adopt an already-submitted server statement by its id, producing
/// an [`ExecutedAsyncStatement`] that can poll [`status`] / await
/// results / cancel — without having been the handle that submitted
Expand Down
60 changes: 58 additions & 2 deletions tests/v0_c_abi_session_test_wiremock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ fn session_test_returns_success_when_server_reachable() {

// The probe reaches the server and succeeds.
assert_eq!(
kernel_session_test(session),
kernel_session_test(session, 0),
KernelStatusCode::Success,
"kernel_session_test must return Success against a reachable server"
);
Expand Down Expand Up @@ -195,7 +195,7 @@ fn session_test_returns_error_when_server_unreachable() {
// Kill the server: the statement round-trip now fails.
drop(server);

let rc = kernel_session_test(session);
let rc = kernel_session_test(session, 0);
assert_ne!(
rc,
KernelStatusCode::Success,
Expand All @@ -205,3 +205,59 @@ fn session_test_returns_error_when_server_unreachable() {
assert_eq!(kernel_session_close(session), KernelStatusCode::Success);
}
}

// odbc#347-C: a non-zero `timeout_secs` bounds the whole probe. When the SELECT 1
// round-trip is slower than the deadline, the probe returns Timeout promptly —
// it does not block for the full server delay (nor the session's retry budget).
#[test]
fn session_test_honours_per_call_timeout() {
let rt = tokio::runtime::Runtime::new().unwrap();
let server =
rt.block_on(async {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/2.0/sql/sessions"))
.respond_with(ResponseTemplate::new(200).set_body_string(
r#"{"session_id":"sess-c-abi-slow","warehouse_id":"test_wh"}"#,
))
.mount(&server)
.await;
// The SELECT 1 statement POST is delayed well beyond the 1s probe
// deadline, so the probe must give up on its own deadline rather than
// wait for this response.
Mock::given(method("POST"))
.and(path("/api/2.0/sql/statements"))
.respond_with(
ResponseTemplate::new(200)
.set_delay(std::time::Duration::from_secs(20))
.set_body_string(select_1_succeeded_body("stmt-slow")),
)
.mount(&server)
.await;
server
});
let uri = server.uri();

unsafe {
let session = open_session(&uri);

// With a 1-second deadline against a 20-second response, the probe must
// return Timeout within a small multiple of the deadline (not ~20s).
let start = std::time::Instant::now();
let rc = kernel_session_test(session, 1);
let elapsed = start.elapsed();

assert_eq!(
rc,
KernelStatusCode::Timeout,
"a probe slower than its per-call deadline must return Timeout"
);
assert!(
elapsed < std::time::Duration::from_secs(10),
"the probe blocked for {:?}, far longer than its 1s deadline",
elapsed
);

assert_eq!(kernel_session_close(session), KernelStatusCode::Success);
}
}
Loading