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 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 }} 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/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(()) } /// ``` 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::>(), + ); +}