From a780a559448f682f1e9b1181e0b08cfd0cfad8c2 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Sat, 30 May 2026 12:21:15 +0000 Subject: [PATCH 1/4] fix(sea): close orphaned statement when execute_and_read fails After ``call_execute_api`` succeeds the SEA statement is open on the server. Two paths into a leak that would otherwise persist until SQL Gateway's ``CommandInactivityTimeout`` (~1h): 1. ``wait_for_completion`` returns ``Error::timeout`` while the server still considers the statement live in PENDING / RUNNING. Terminal FAILED / CANCELED is the server's own cleanup signal and doesn't need a CloseStatement, but the polling-timeout path does. 2. ``create_reader`` fails. The most likely sub-failure is ``ResultPostProcessor::new`` -> ``StreamingCloudFetchProvider:: get_schema`` eagerly downloading chunk 0 to extract the result schema; a non-retriable 4xx / persistent 5xx on that GET propagates up. The probe in driver-test PR #410's CLOUDFETCH-016 caught this: on a perpetual ``cloudfetch_500``, the kernel exhausted retries and never issued ``DELETE /api/2.0/sql/statements/{id}``. Capture the ``statement_id`` from the initial response (before ``wait_for_completion``) and fire a best-effort close on both failure paths via ``close_statement``. Since the trait method already swallows its own errors, the wrapper here is just a logging seam that attributes which phase failed so traces stay diagnosable. New wiremock reproducer in ``tests/v0_execute_wiremock.rs`` (``execute_cloudfetch_chunk0_failure_closes_statement``): mounts a SUCCEEDED execute response with external_links pointing at the mock server, then 404s the chunk-0 GET. Asserts the mock observes a DELETE on the statement. Test fails on baseline (5 chunk-0 GET retries then no DELETE); passes with the fix in this commit. End-to-end verified against the driver-test proxy suite's CLOUDFETCH-016-equivalent path: raised=1 CloseStatement=1 DeleteSession=1 vs. baseline: raised=1 CloseStatement=0 DeleteSession=1 Closes the kernel half of the orphaned-op bug surfaced by databricks/databricks-driver-test#410. Signed-off-by: Vikrant Puppala --- src/client/sea.rs | 75 +++++++++++++++++- tests/v0_execute_wiremock.rs | 148 +++++++++++++++++++++++++++++++++++ 2 files changed, 219 insertions(+), 4 deletions(-) diff --git a/src/client/sea.rs b/src/client/sea.rs index a962937b..7f23d389 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -35,7 +35,7 @@ use reqwest::Method; use std::collections::HashMap; use std::sync::{Arc, OnceLock}; use tokio::runtime::Handle as RuntimeHandle; -use tracing::debug; +use tracing::{debug, warn}; /// Internal terminal-outcome for a single SEA statement response. /// @@ -451,10 +451,40 @@ impl SeaRestTransport { params: &ExecuteParams, request_type: RequestType, ) -> Result { + // After call_execute_api succeeds, the SEA statement is open + // on the server. Any subsequent failure before we hand back + // an ExecuteResult (which wraps it in an ExecutedStatement + // whose Drop / explicit close() cleans up) would orphan the + // server-side statement until SQL Gateway's + // CommandInactivityTimeout (~1h) reclaims it. Two known + // paths into that gap: + // + // - wait_for_completion times out (`Error::timeout`) while + // the server still considers the statement live in + // PENDING / RUNNING. (Terminal FAILED / CANCELED is the + // server's own cleanup signal — no CloseStatement + // needed.) + // - create_reader fails. The most likely sub-failure today + // is `ResultPostProcessor::new -> + // StreamingCloudFetchProvider::get_schema` eagerly + // downloading chunk 0 to extract the result schema; a + // non-retriable 4xx / 5xx on that GET propagates up. + // + // Capture the statement_id from the initial response so we + // can issue a best-effort close on either path. let response = self .call_execute_api(session_id, sql, params, request_type) .await?; - let response = self.wait_for_completion(response).await?; + let statement_id = response.statement_id.clone(); + + let response = match self.wait_for_completion(response).await { + Ok(r) => r, + Err(e) => { + self.close_orphaned_statement(&statement_id, "wait_for_completion") + .await; + return Err(e); + } + }; let reader_factory = self.reader_factory()?; // `create_reader` wraps in a `ResultPostProcessor` // internally, so the reader returned here already carries @@ -465,9 +495,17 @@ impl SeaRestTransport { // Arrow shape collapses (VARIANT → Utf8, intervals → Interval, // GEOMETRY/GEOGRAPHY → Utf8). The post-processor also handles // the optional complex-types-as-JSON rewrite in the same pass. - let reader = reader_factory + let reader = match reader_factory .create_reader(&response.statement_id, &response) - .await?; + .await + { + Ok(r) => r, + Err(e) => { + self.close_orphaned_statement(&statement_id, "create_reader") + .await; + return Err(e); + } + }; // The full `status` is carried forward so the executed handle // can skip a redundant CloseStatement when the server already @@ -481,6 +519,35 @@ impl SeaRestTransport { status: response.status, }) } + + /// Best-effort close for a server-side statement we opened but + /// can't hand off to an `ExecutedStatement` because of a failure + /// in `wait_for_completion` or `create_reader`. The trait method + /// `close_statement` already swallows its own errors (line 797); + /// the wrapper here is just a logging seam so a future failure + /// to clean up shows up in traces with the failing-phase + /// attribution (`wait_for_completion` vs `create_reader`). + async fn close_orphaned_statement(&self, statement_id: &str, phase: &str) { + debug!( + statement_id = %statement_id, + phase = %phase, + "execute_and_read: closing orphaned statement after failure" + ); + if let Err(e) = ::close_statement(self, statement_id).await { + // `close_statement` is documented as best-effort and + // returns Ok even on inner failure (see body), but the + // signature is fallible so future implementations can + // surface real errors. Demote to warn — the caller is + // already returning the originating error. + warn!( + statement_id = %statement_id, + phase = %phase, + error = %e, + "execute_and_read: orphan-close failed; statement may linger \ + until SQL Gateway CommandInactivityTimeout" + ); + } + } } /// Convert a parsed `GetChunksResponse` into the kernel-facing diff --git a/tests/v0_execute_wiremock.rs b/tests/v0_execute_wiremock.rs index 7c1c5a89..237f0ece 100644 --- a/tests/v0_execute_wiremock.rs +++ b/tests/v0_execute_wiremock.rs @@ -869,3 +869,151 @@ async fn execute_failed_carries_extended_status_fields_onto_error() { Some(r#"{"errorClass":"TABLE_OR_VIEW_NOT_FOUND","messageTemplate":"..."}"#) ); } + +/// Reproducer for the orphaned-statement bug observed against the +/// proxy-test suite's CLOUDFETCH-016 (databricks-driver-test PR #410). +/// +/// `Statement::execute()` is supposed to be all-or-nothing: either it +/// hands back an `ExecutedStatement` whose `close()` cleans up +/// server-side state, OR it returns an error and the kernel cleans +/// up internally. Today the latter half is missing for the CloudFetch +/// path: when the server returns a `SUCCEEDED` response carrying +/// `external_links` and the kernel's reader-construction reads chunk +/// 0 (in `ResultPostProcessor::new` -> `StreamingCloudFetchProvider:: +/// get_schema` -> eager download) and that download fails, the +/// SUCCEEDED statement on the server is leaked until the SQL +/// Gateway's `CommandInactivityTimeout` (~1h) reclaims it. The +/// kernel never issues `DELETE /api/2.0/sql/statements/{id}`. +/// +/// This test mounts: +/// 1. `POST /api/2.0/sql/statements` returning a SUCCEEDED body +/// with `external_links` pointing back at the mock server. +/// 2. `GET` on that link returning HTTP 500 (simulating an Azure +/// Blob / S3 transient failure that doesn't trigger urllib3's +/// retry policy in our case). +/// +/// Expectation after the fix: `Statement::execute()` returns Err, +/// AND the mock records a `DELETE /api/2.0/sql/statements/stmt-cf-leak` +/// before the test ends. +#[tokio::test] +async fn execute_cloudfetch_chunk0_failure_closes_statement() { + let server = MockServer::start().await; + mount_create_session(&server).await; + mount_delete_session(&server).await; + + let statement_id = "stmt-cf-leak"; + let chunk_path = format!("/cloud-fetch/{statement_id}/chunk-0.arrow"); + let chunk_url = format!("{}{}", server.uri(), chunk_path); + + // POST /statements: SUCCEEDED + external_links pointing at the + // mock-served chunk URL. The kernel will read chunk 0 eagerly in + // ResultPostProcessor::new to extract the result schema, so chunk + // 0's GET fires before execute() returns. + let exec_body = json!({ + "statement_id": statement_id, + "status": { "state": "SUCCEEDED" }, + "manifest": { + "format": "ARROW_STREAM", + "schema": { + "column_count": 1, + "columns": [{ + "name": "id", + "type_name": "BIGINT", + "type_text": "BIGINT", + "position": 0, + }], + }, + "total_chunk_count": 1, + "total_row_count": 1, + "total_byte_count": 1024, + "truncated": false, + }, + "result": { + "external_links": [{ + "external_link": chunk_url, + "expiration": "2099-01-01T00:00:00.000Z", + "chunk_index": 0, + "row_offset": 0, + "row_count": 1, + "byte_count": 1024, + }], + }, + }) + .to_string(); + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(ResponseTemplate::new(200).set_body_string(exec_body)) + .mount(&server) + .await; + + // Chunk-0 download fails with HTTP 404 — a non-retryable client + // error. The kernel's CloudFetch downloader treats 5xx as + // transient and retries up to ~30 times, which would make this + // test run for minutes; 404 hits the same propagation path + // (downloader -> ResultPostProcessor::new -> execute_and_read) + // on the first attempt. The bug we're reproducing is independent + // of which 4xx/5xx code surfaces the failure — what matters is + // that download fails after the SUCCEEDED execute response. + Mock::given(method("GET")) + .and(path(chunk_path.as_str())) + .respond_with(ResponseTemplate::new(404).set_body_string("Not Found")) + .mount(&server) + .await; + + // DELETE /statements/{id}: success. We do NOT mount it with + // `expect()` so that absence of the call shows up as a missing + // entry in `received_requests`, not as a wiremock failure + // message ("expected mock not called"). + Mock::given(method("DELETE")) + .and(path(format!("/api/2.0/sql/statements/{statement_id}"))) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(&server) + .await; + + let session = open_session(&server).await; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT id FROM range(2000000)"); + + let err = stmt + .execute() + .await + .err() + .expect("execute must fail when chunk-0 returns HTTP 500"); + + // The error variant isn't load-bearing here; the close path is. + // Log so a regression that changes the surfaced error shape is + // visible at test-output time without burying the close-assert. + eprintln!("[reproducer] execute() returned: {err:?}"); + + // Defensive close — closes any state the failing execute() + // tracked locally. Mirrors what the Python connector does (and + // the C# canonical's `DatabricksCompositeReader.Dispose`). + let _ = stmt.close().await; + + // Drop the session too so any lingering shutdown paths run. + let _ = session.close().await; + + // The fix: after the eager-chunk-0 failure, the kernel must + // issue DELETE /api/2.0/sql/statements/{id} so the SUCCEEDED + // server-side statement doesn't linger until + // CommandInactivityTimeout (~1h). + let recorded = server + .received_requests() + .await + .expect("wiremock received_requests must be available"); + let delete_path = format!("/api/2.0/sql/statements/{statement_id}"); + let deletes: Vec<_> = recorded + .iter() + .filter(|r| r.method == wiremock::http::Method::DELETE && r.url.path() == delete_path) + .collect(); + assert!( + !deletes.is_empty(), + "expected at least one DELETE {delete_path} after chunk-0 download \ + failure; observed requests: {observed:?}", + delete_path = delete_path, + observed = recorded + .iter() + .map(|r| format!("{} {}", r.method, r.url.path())) + .collect::>(), + ); +} From f6d0c30358db8d6842bb70f65d03f02f6a455649 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Mon, 1 Jun 2026 05:16:56 +0000 Subject: [PATCH 2/4] fix: rustfmt + non-exhaustive TlsConfig doc tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Apply cargo fmt to arrow_parser.rs and fix the TlsConfig doc examples in config.rs / session.rs, which used struct-literal syntax with ..default() against a #[non_exhaustive] struct — illegal from the doc tests' external-crate context. Construct via TlsConfig::default() and assign public fields instead. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- src/config.rs | 15 +++++++-------- src/reader/cloudfetch/arrow_parser.rs | 9 ++++----- src/session.rs | 6 ++---- 3 files changed, 13 insertions(+), 17 deletions(-) diff --git a/src/config.rs b/src/config.rs index 0d9fbb84..1397fcf5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -356,21 +356,20 @@ pub struct ProxyConfig {} /// The kernel exposes only fields that the internal rustls plumbing /// already supports — cert pinning and FIPS mode are *not* in scope. /// +/// `TlsConfig` is `#[non_exhaustive]`, so construct it from +/// [`TlsConfig::default`] and assign the public fields you need: +/// /// ```no_run /// # use databricks_sql_kernel::TlsConfig; /// // From a file path: -/// let from_file = TlsConfig { -/// custom_ca_cert: Some(std::fs::read("/etc/ssl/corp-ca.pem").unwrap()), -/// ..TlsConfig::default() -/// }; +/// let mut from_file = TlsConfig::default(); +/// from_file.custom_ca_cert = Some(std::fs::read("/etc/ssl/corp-ca.pem").unwrap()); /// /// // From an in-memory buffer (the napi-rs `Buffer` / pyo3 `bytes` /// // path — no tempfile shim needed): /// let pem_bytes: Vec = b"-----BEGIN CERTIFICATE-----\n...".to_vec(); -/// let from_bytes = TlsConfig { -/// custom_ca_cert: Some(pem_bytes), -/// ..TlsConfig::default() -/// }; +/// let mut from_bytes = TlsConfig::default(); +/// from_bytes.custom_ca_cert = Some(pem_bytes); /// # let _ = (from_file, from_bytes); /// ``` // diff --git a/src/reader/cloudfetch/arrow_parser.rs b/src/reader/cloudfetch/arrow_parser.rs index dcf3cec0..e6f6f50a 100644 --- a/src/reader/cloudfetch/arrow_parser.rs +++ b/src/reader/cloudfetch/arrow_parser.rs @@ -63,9 +63,9 @@ pub fn parse_arrow_ipc(data: &[u8], compression: CompressionCodec) -> Result Result<(), Box> { - /// let tls = TlsConfig { - /// custom_ca_cert: Some(std::fs::read("/etc/ssl/corp-ca.pem")?), - /// ..TlsConfig::default() - /// }; + /// let mut tls = TlsConfig::default(); + /// tls.custom_ca_cert = Some(std::fs::read("/etc/ssl/corp-ca.pem")?); /// let _builder = Session::builder().tls(tls); /// # Ok(()) } /// ``` From f044ed97708a149769bf3186540ed86c9c8cd3cc Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Mon, 1 Jun 2026 05:25:54 +0000 Subject: [PATCH 3/4] ci: point E2E DATABRICKS_HTTP_PATH at the existing azure-prod secret MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The rust-e2e workflow mapped DATABRICKS_HTTP_PATH from secrets.TEST_PECO_WAREHOUSE_HTTP_PATH, but the azure-prod environment has no secret by that name — its secrets are DATABRICKS_HOST, DATABRICKS_HTTP_PATH, DATABRICKS_TOKEN. The unknown name resolved to empty, so require_host_and_path() panicked with 'DATABRICKS_HTTP_PATH must be set' and the whole v0 E2E suite failed. Point it at the secret that actually exists. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- .github/workflows/rust-e2e.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/rust-e2e.yml b/.github/workflows/rust-e2e.yml index 1d213404..2d58ece2 100644 --- a/.github/workflows/rust-e2e.yml +++ b/.github/workflows/rust-e2e.yml @@ -66,7 +66,7 @@ jobs: environment: azure-prod env: DATABRICKS_HOST: ${{ secrets.DATABRICKS_HOST }} - DATABRICKS_HTTP_PATH: ${{ secrets.TEST_PECO_WAREHOUSE_HTTP_PATH }} + DATABRICKS_HTTP_PATH: ${{ secrets.DATABRICKS_HTTP_PATH }} DATABRICKS_TOKEN: ${{ secrets.DATABRICKS_TOKEN }} DATABRICKS_TEST_CLIENT_ID: ${{ secrets.DATABRICKS_TEST_CLIENT_ID }} DATABRICKS_TEST_CLIENT_SECRET: ${{ secrets.DATABRICKS_TEST_CLIENT_SECRET }} From 98db2153b2535137d8dde656874a636a9823abf6 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Mon, 1 Jun 2026 05:28:38 +0000 Subject: [PATCH 4/4] ci: route tls-rustls build through the JFrog cargo proxy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The check-tls-rustls job was the only cargo job in pr-checks.yml missing the ./.github/actions/setup-jfrog step that its sibling clippy/test jobs run. On the protected runners, direct crates.io access is blocked (go/hardened-gha); without setup-jfrog the cargo fetch has no db-cargo-remote config or OIDC token, so dependency download fails with 'SSL connect error (unexpected eof while reading)' fetching arrow-array — the recurring fast-fail seen on every run. Add setup-jfrog and align the checkout / toolchain pins with the other jobs. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- .github/workflows/pr-checks.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index c86de823..8f3833e2 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -107,9 +107,13 @@ jobs: group: databricks-protected-runner-group labels: linux-ubuntu-latest steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - uses: ./.github/actions/setup-jfrog + with: + cargo: "true" - - uses: actions-rust-lang/setup-rust-toolchain@1780873c7b576612439a134613cc4cc74ce5538c # v1.15.2 + - uses: actions-rust-lang/setup-rust-toolchain@46268bd060767258de96ed93c1251119784f2ab6 # v1.16.1 with: toolchain: stable components: clippy