diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index c67c8b5b..c78df105 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -56,12 +56,11 @@ * - **A result stream borrows its executed handle.** Closing the executed * handle invalidates any stream obtained from it: subsequent stream * calls return `InvalidStatementHandle` (a defined error, not UB). - * - **Close is best-effort async.** `kernel_session_close` initiates the - * server-side delete before returning — a detached task runs it on the - * kernel's process-wide runtime — but does not wait for completion. A - * process that exits immediately after `kernel_session_close` may drop - * the detached task before it runs, leaving the server session to expire - * on its own idle timeout. + * - **Close is awaited.** `kernel_session_close` waits for the server-side + * delete to complete and flushes close-session telemetry before returning. + * If close fails, the kernel still schedules best-effort cleanup when the + * consumed session handle is dropped, but the status code reports the + * awaited close failure to the caller. * - **Close the session LAST.** Because close initiates the server-side * delete, any handle still open against that session — a statement / * executed handle, or a metadata result stream (which holds its own diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 017f8ae0..af85b7d1 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -1624,9 +1624,8 @@ fn build_session(config: KernelSessionConfig) -> Result ); return KernelStatusCode::InvalidArgument; } - // Reclaim the box and initiate the fire-and-forget `DeleteSession` - // right now. We call `initiate_delete()` explicitly rather than - // relying on `Drop`: a still-live statement / executed handle holds - // its own `Arc` clone, so `SessionInner::Drop` (which - // only fires when the *last* Arc drops) would otherwise defer the - // server-side delete until those handles are released — contradicting - // the header's "close initiates the delete" contract. `initiate_delete` - // is idempotent, so the eventual `Drop` becomes a no-op. We still don't - // `block_on` an awaited close — that would make close block on the - // network for no caller benefit. - let session = Box::from_raw(session as *mut Session); - session.initiate_delete(); - drop(session); - KernelStatusCode::Success + // Reclaim the box and move the `Session` into the awaited close. On close + // failure, `Session::close` leaves the closed flag unset; dropping the + // consumed session still triggers the fire-and-forget fallback delete. + let session = *Box::from_raw(session as *mut Session); + match block_on_ffi(move || session.close()) { + Ok(()) => KernelStatusCode::Success, + Err(code) => code, + } } /// Report whether a session is still **open** (its server-side delete has @@ -2815,6 +2808,82 @@ mod tests { } } + #[test] + fn kernel_session_close_exports_delete_session_telemetry() { + use crate::telemetry::test_support::CapturingTelemetryExporter; + use serde_json::Value; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let rt = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .expect("test runtime"); + let (server, session, exporter) = 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-cabi-telemetry-close","warehouse_id":"test_wh"}"#, + )) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/sess-cabi-telemetry-close")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + + let exporter = CapturingTelemetryExporter::default(); + let telemetry = TelemetryConfig { + enabled: true, + ..Default::default() + } + .with_exporter(std::sync::Arc::new(exporter.clone())); + let session = Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") + .expect("valid http_path"), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + identity_federation_client_id: None, + }) + .telemetry(telemetry) + .open() + .await + .expect("session must open"); + (server, session, exporter) + }); + + let session = Box::into_raw(Box::new(session)) as *mut kernel_session_t; + assert_eq!( + unsafe { kernel_session_close(session) }, + KernelStatusCode::Success + ); + + let operations = exporter + .requests() + .into_iter() + .flat_map(|request| request.proto_logs) + .map(|log| { + let value: Value = serde_json::from_str(&log).expect("valid frontend log json"); + assert_eq!( + value["entry"]["sql_driver_log"]["session_id"], + "sess-cabi-telemetry-close" + ); + value["entry"]["sql_driver_log"]["sql_operation"]["operation_detail"] + ["operation_type"] + .as_str() + .expect("operation_type string") + .to_string() + }) + .collect::>(); + + assert_eq!(operations, vec!["CREATE_SESSION", "DELETE_SESSION"]); + drop(server); + } + #[test] fn set_driver_system_configuration_records_optional_fields() { unsafe { diff --git a/src/session.rs b/src/session.rs index 8ceaa68a..f7547f43 100644 --- a/src/session.rs +++ b/src/session.rs @@ -515,23 +515,13 @@ impl Session { .await } - /// Initiate the fire-and-forget server-side `DeleteSession` now, - /// without awaiting it or consuming `self`. Idempotent. Used by the C - /// ABI's `kernel_session_close` so the delete is initiated on close - /// even when child handles still hold `Arc` clones - /// (otherwise it would be deferred until the last handle drops). For - /// an awaitable close that surfaces failure, use [`Session::close`]. - pub(crate) fn initiate_delete(&self) { - self.inner.initiate_delete(); - } - /// Whether this session is still open — i.e. its server-side delete - /// has not been initiated (via [`Session::close`] or - /// [`Session::initiate_delete`]). This is a **local** check, not a - /// server round-trip: it reports whether the handle has been - /// closed/superseded, so a caller doesn't drive an already-deleted - /// session. It does **not** detect a server-side idle timeout or a - /// dropped network link. Backs the C ABI's `kernel_session_is_open`. + /// has not been initiated via [`Session::close`] or drop cleanup. This is + /// a **local** check, not a server round-trip: it reports whether the + /// handle has been closed/superseded, so a caller doesn't drive an + /// already-deleted session. It does **not** detect a server-side idle + /// timeout or a dropped network link. Backs the C ABI's + /// `kernel_session_is_open`. pub(crate) fn is_open(&self) -> bool { !self.inner.closed.load(std::sync::atomic::Ordering::Acquire) } @@ -1884,7 +1874,7 @@ mod is_open_tests { session.is_open(), "a freshly-opened session must report open" ); - session.initiate_delete(); + session.inner.initiate_delete(); assert!( !session.is_open(), "after initiate_delete the session must report not-open"