From b451e1aa4521980a75521efa01ad05031e4afe1c Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 08:55:53 +0000 Subject: [PATCH 01/11] fix(cloudfetch): refresh a link that storage rejects with 401/403/404 A CloudFetch download refused with 401, 403 or 404 was retried with the same presigned URL: the provider refreshes a link only on time-based expiry, so a URL whose signature storage rejected (or GCS's 404 for an expired one) could never succeed on retry. Mark the refused URL and refresh the chunk's link before the next attempt; the batched refresh no longer treats the refused URL as fresh. The failure still counts against the download attempt budget. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- NEXT_CHANGELOG.md | 1 + src/reader/cloudfetch/streaming_provider.rs | 198 +++++++++++++++++++- 2 files changed, 195 insertions(+), 4 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 6aa75289..04b799c1 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -26,6 +26,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Fixed - `Session::open` authenticates once before resolving feature flags. A failed OAuth token request now fails the open immediately instead of being sent a second time by CreateSession. +- A CloudFetch download that cloud storage rejects with 401, 403 or 404 (an expired or invalid presigned URL) now refreshes the chunk's link before retrying, instead of retrying the same URL. The retry still counts against the download attempt budget. --- *Note: When making changes, please add your change under the appropriate diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index 5fbab8d7..da3eebbd 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -944,6 +944,10 @@ impl StreamingCloudFetchProvider { let deadline = (!ctx.download_timeout.is_zero()) .then(|| std::time::Instant::now() + ctx.download_timeout); + // A presigned URL cloud storage refused (401/403/404). The next attempt + // refreshes the link even though it has not expired. + let mut rejected_url: Option = None; + loop { if ctx.cancel_token.is_cancelled() { return Err(Error::invalid_state().message("Download cancelled")); @@ -974,7 +978,12 @@ impl StreamingCloudFetchProvider { let stored_link = ctx.chunks.get(&chunk_index).and_then(|e| e.link.clone()); match stored_link { - Some(link) if !link.is_expired() => link, + Some(link) + if !link.is_expired() + && rejected_url.as_deref() != Some(link.url.as_str()) => + { + link + } _ => { debug!( "Link for chunk {} missing or expired; \ @@ -988,8 +997,9 @@ impl StreamingCloudFetchProvider { // keeps the deadline genuinely end-to-end across // the link-refresh step, matching the loop-level // comment above. - let refresh = Self::refresh_links_batch( + let refresh = Self::refresh_links_batch_replacing( chunk_index, + rejected_url.as_deref(), &ctx.link_fetcher, &ctx.chunks, &ctx.refresh_coordinator, @@ -1020,6 +1030,9 @@ impl StreamingCloudFetchProvider { )) .with_cause(e) })?; + // Download whatever URL the refresh produced; a + // repeat rejection is charged to the attempt budget. + rejected_url = None; // After a successful refresh, the link // MUST exist and be fresh — `refresh_links_batch` // returns Err otherwise (missing chunk in @@ -1124,6 +1137,18 @@ impl StreamingCloudFetchProvider { if attempts >= ctx.max_retries { return Err(e); } + // Storage refused the presigned URL itself (an expired or + // invalid signature; GCS answers 404 for an expired one), so + // retrying it cannot succeed. Refresh the link instead, without + // sleeping: the failure was charged above. + if let Some(status @ (401 | 403 | 404)) = e.http_status { + debug!( + "Chunk {} download got HTTP {}; refreshing the link before retry", + chunk_index, status, + ); + rejected_url = Some(link.url.clone()); + continue; + } // Stale-snapshot detection. Two ways a download // can fail against a URL that became stale while // the request was in flight: @@ -1288,6 +1313,34 @@ impl StreamingCloudFetchProvider { cancel_token: &CancellationToken, statement_id: Option<&str>, ) -> Result<()> { + Self::refresh_links_batch_replacing( + start_chunk_index, + None, + link_fetcher, + chunks, + coordinator, + cancel_token, + statement_id, + ) + .await + } + + /// [`Self::refresh_links_batch`], where `rejected_url` (when set) is a + /// presigned URL cloud storage refused: a cached link with that URL needs + /// a refresh even though it has not expired. + async fn refresh_links_batch_replacing( + start_chunk_index: i64, + rejected_url: Option<&str>, + link_fetcher: &Arc, + chunks: &Arc>, + coordinator: &Arc, + cancel_token: &CancellationToken, + statement_id: Option<&str>, + ) -> Result<()> { + // A cached link is usable unless it expired or storage rejected its URL. + let is_usable = |link: &crate::types::CloudFetchLink| { + !link.is_expired() && rejected_url != Some(link.url.as_str()) + }; // Display helper: `""` is loud enough for ops // to notice missing statement_id in log filters. let sid = statement_id.unwrap_or(""); @@ -1361,7 +1414,7 @@ impl StreamingCloudFetchProvider { let url_changed = pre_attempt_url .as_ref() .is_some_and(|prev| *prev != link.url); - if url_changed || !link.is_expired() { + if url_changed || is_usable(link) { debug!( statement_id = %sid, "Concurrent refresh delivered a {} link for chunk {}; \ @@ -1411,7 +1464,7 @@ impl StreamingCloudFetchProvider { let url_changed = pre_attempt_url .as_ref() .is_some_and(|prev| *prev != link.url); - if url_changed || !link.is_expired() { + if url_changed || is_usable(link) { debug!( statement_id = %sid, "Batched refresh for chunk {} skipped after claim — \ @@ -1955,6 +2008,143 @@ mod tests { ); } + #[tokio::test] + async fn rejected_presigned_url_is_refreshed_before_retry() { + for status in [401, 403, 404] { + assert_download_recovers(status, true).await; + } + // Other 4xx statuses keep the same-URL retry. + assert_download_recovers(400, false).await; + } + + async fn assert_download_recovers(status: u16, expect_refresh: bool) { + use crate::client::retry::{build_retry_configs, RetryConfig}; + use crate::client::{DatabricksHttpClient, HttpClientConfig}; + use crate::types::sea::CompressionCodec; + use arrow_array::Int32Array; + use arrow_ipc::writer::StreamWriter; + use arrow_schema::{DataType, Field, Schema}; + use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from(vec![1, 2, 3]))], + ) + .unwrap(); + let mut ipc_bytes = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut ipc_bytes, &schema).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + } + + // The original URL fails once; a refreshed URL is served by a second path. + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/chunk-0-old.arrow")) + .respond_with(ResponseTemplate::new(status)) + .up_to_n_times(1) + .mount(&server) + .await; + for chunk_path in ["/chunk-0-old.arrow", "/chunk-0-new.arrow"] { + Mock::given(method("GET")) + .and(path(chunk_path)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(ipc_bytes.clone())) + .mount(&server) + .await; + } + + #[derive(Debug)] + struct RefreshingFetcher { + fresh_url: String, + refresh_calls: AtomicUsize, + } + + #[async_trait::async_trait] + impl ChunkLinkFetcher for RefreshingFetcher { + async fn fetch_links(&self, _: i64, _: i64) -> Result { + unreachable!() + } + + async fn refetch_link(&self, _: i64, _: i64) -> Result { + unreachable!() + } + + async fn refetch_links_from(&self, _: i64, _: i64) -> Result> { + self.refresh_calls.fetch_add(1, AtomicOrdering::SeqCst); + Ok(vec![CloudFetchLink { + url: self.fresh_url.clone(), + ..create_test_link(0) + }]) + } + } + + let retry = RetryConfig { + max_retries: 0, + ..RetryConfig::default() + }; + let http_client = Arc::new( + DatabricksHttpClient::new( + HttpClientConfig::default(), + build_retry_configs(&retry, &HashMap::new()), + ) + .unwrap(), + ); + let fetcher = Arc::new(RefreshingFetcher { + fresh_url: format!("{}/chunk-0-new.arrow", server.uri()), + refresh_calls: AtomicUsize::new(0), + }); + let chunks = Arc::new(DashMap::new()); + let original = CloudFetchLink { + url: format!("{}/chunk-0-old.arrow", server.uri()), + ..create_test_link(0) + }; + chunks.insert(0, entry_with_state(original, ChunkState::Downloading)); + let ctx = DownloadCtx { + downloader: Arc::new(ChunkDownloader::new( + http_client, + CompressionCodec::None, + 0.1, + )), + link_fetcher: fetcher.clone(), + chunks, + refresh_coordinator: Arc::new(RefreshCoordinator::default()), + cancel_token: CancellationToken::new(), + statement_id: None, + metrics: Arc::new(CloudFetchMetrics::new(Some(1))), + max_retries: 3, + retry_delay: std::time::Duration::ZERO, + download_timeout: std::time::Duration::ZERO, + }; + + let batches = StreamingCloudFetchProvider::download_chunk_with_retry(0, &ctx) + .await + .unwrap_or_else(|e| panic!("HTTP {status}: one failed download must recover: {e}")); + assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 3); + + let paths: Vec = server + .received_requests() + .await + .unwrap() + .iter() + .map(|r| r.url.path().to_string()) + .collect(); + let (expected_paths, expected_refreshes) = if expect_refresh { + (vec!["/chunk-0-old.arrow", "/chunk-0-new.arrow"], 1) + } else { + (vec!["/chunk-0-old.arrow", "/chunk-0-old.arrow"], 0) + }; + assert_eq!(paths, expected_paths, "HTTP {status}: downloaded URLs"); + assert_eq!( + fetcher.refresh_calls.load(AtomicOrdering::SeqCst), + expected_refreshes, + "HTTP {status}: link refreshes", + ); + } + // ─── End-to-end download deadline (issue #321 / audit H05) ─────────── // // These tests exercise `download_chunk_with_retry`'s absolute From bfadc8a257ba06d1c4493810e7c01aea72cb4b3a Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 09:06:58 +0000 Subject: [PATCH 02/11] fix(cloudfetch): back off before refreshing a link that was refused again Review follow-up. The first refusal still refreshes at once; when a refreshed URL is refused too, the attempt waits the usual retry delay before the next refresh, so a persistently refused chunk does not issue back-to-back refresh RPCs. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- src/reader/cloudfetch/streaming_provider.rs | 107 +++++++++++++++++++- 1 file changed, 104 insertions(+), 3 deletions(-) diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index da3eebbd..ad70b577 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -947,6 +947,7 @@ impl StreamingCloudFetchProvider { // A presigned URL cloud storage refused (401/403/404). The next attempt // refreshes the link even though it has not expired. let mut rejected_url: Option = None; + let mut refused_before = false; loop { if ctx.cancel_token.is_cancelled() { @@ -1139,15 +1140,19 @@ impl StreamingCloudFetchProvider { } // Storage refused the presigned URL itself (an expired or // invalid signature; GCS answers 404 for an expired one), so - // retrying it cannot succeed. Refresh the link instead, without - // sleeping: the failure was charged above. + // retrying it cannot succeed: refresh the link instead. The + // first refusal refreshes at once; if a refreshed URL is refused + // too, fall through to the backoff below before refreshing again. if let Some(status @ (401 | 403 | 404)) = e.http_status { debug!( "Chunk {} download got HTTP {}; refreshing the link before retry", chunk_index, status, ); rejected_url = Some(link.url.clone()); - continue; + if !refused_before { + refused_before = true; + continue; + } } // Stale-snapshot detection. Two ways a download // can fail against a URL that became stale while @@ -2145,6 +2150,102 @@ mod tests { ); } + #[tokio::test] + async fn repeatedly_refused_url_backs_off_before_refreshing_again() { + use crate::client::retry::{build_retry_configs, RetryConfig}; + use crate::client::{DatabricksHttpClient, HttpClientConfig}; + use crate::types::sea::CompressionCodec; + use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; + use wiremock::matchers::method; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + const RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(200); + + // Storage refuses every URL, including refreshed ones. + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(403)) + .mount(&server) + .await; + + #[derive(Debug)] + struct NewUrlFetcher { + base: String, + refresh_calls: AtomicUsize, + } + + #[async_trait::async_trait] + impl ChunkLinkFetcher for NewUrlFetcher { + async fn fetch_links(&self, _: i64, _: i64) -> Result { + unreachable!() + } + + async fn refetch_link(&self, _: i64, _: i64) -> Result { + unreachable!() + } + + async fn refetch_links_from(&self, _: i64, _: i64) -> Result> { + let n = self.refresh_calls.fetch_add(1, AtomicOrdering::SeqCst) + 1; + Ok(vec![CloudFetchLink { + url: format!("{}/chunk-0-{n}.arrow", self.base), + ..create_test_link(0) + }]) + } + } + + let retry = RetryConfig { + max_retries: 0, + ..RetryConfig::default() + }; + let http_client = Arc::new( + DatabricksHttpClient::new( + HttpClientConfig::default(), + build_retry_configs(&retry, &HashMap::new()), + ) + .unwrap(), + ); + let fetcher = Arc::new(NewUrlFetcher { + base: server.uri(), + refresh_calls: AtomicUsize::new(0), + }); + let chunks = Arc::new(DashMap::new()); + let original = CloudFetchLink { + url: format!("{}/chunk-0-0.arrow", server.uri()), + ..create_test_link(0) + }; + chunks.insert(0, entry_with_state(original, ChunkState::Downloading)); + let ctx = DownloadCtx { + downloader: Arc::new(ChunkDownloader::new( + http_client, + CompressionCodec::None, + 0.1, + )), + link_fetcher: fetcher.clone(), + chunks, + refresh_coordinator: Arc::new(RefreshCoordinator::default()), + cancel_token: CancellationToken::new(), + statement_id: None, + metrics: Arc::new(CloudFetchMetrics::new(Some(1))), + max_retries: 3, + retry_delay: RETRY_DELAY, + download_timeout: std::time::Duration::ZERO, + }; + + let started = std::time::Instant::now(); + let error = StreamingCloudFetchProvider::download_chunk_with_retry(0, &ctx) + .await + .expect_err("a URL storage always refuses must fail"); + assert_eq!(error.http_status, Some(403)); + assert_eq!(server.received_requests().await.unwrap().len(), 3); + assert_eq!(fetcher.refresh_calls.load(AtomicOrdering::SeqCst), 2); + // The first refusal refreshes at once; the refused refreshed URL waits one backoff. + assert!( + started.elapsed() >= RETRY_DELAY, + "expected one backoff, took {:?}", + started.elapsed() + ); + } + // ─── End-to-end download deadline (issue #321 / audit H05) ─────────── // // These tests exercise `download_chunk_with_retry`'s absolute From 5b2e37f8b252fc80935735cef57948c35216c3cb Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 09:30:24 +0000 Subject: [PATCH 03/11] test(cloudfetch): bound the backoff test from above Review follow-up: assert exactly one retry_delay, so the test fails if the first refusal also sleeps. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- src/reader/cloudfetch/streaming_provider.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index ad70b577..529f999b 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -2159,7 +2159,7 @@ mod tests { use wiremock::matchers::method; use wiremock::{Mock, MockServer, ResponseTemplate}; - const RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(200); + const RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(500); // Storage refuses every URL, including refreshed ones. let server = MockServer::start().await; @@ -2235,14 +2235,15 @@ mod tests { let error = StreamingCloudFetchProvider::download_chunk_with_retry(0, &ctx) .await .expect_err("a URL storage always refuses must fail"); + let elapsed = started.elapsed(); assert_eq!(error.http_status, Some(403)); assert_eq!(server.received_requests().await.unwrap().len(), 3); assert_eq!(fetcher.refresh_calls.load(AtomicOrdering::SeqCst), 2); - // The first refusal refreshes at once; the refused refreshed URL waits one backoff. + // Exactly one backoff: the first refusal refreshes at once, and only the + // refused refreshed URL waits before the next refresh. assert!( - started.elapsed() >= RETRY_DELAY, - "expected one backoff, took {:?}", - started.elapsed() + elapsed >= RETRY_DELAY && elapsed < RETRY_DELAY * 2, + "expected exactly one backoff of {RETRY_DELAY:?}, took {elapsed:?}" ); } From af0d711052fb92040b03784dcc0d5cdd8f7715fc Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 10:07:31 +0000 Subject: [PATCH 04/11] fix(cloudfetch): log why a link is refreshed; widen the backoff test margin Review follow-up: the refresh log names a storage rejection, and the backoff test uses a 1s delay so its exactly-one-backoff bound leaves a 1s margin on slow runners. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- src/reader/cloudfetch/streaming_provider.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index 529f999b..a69c5d49 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -987,9 +987,13 @@ impl StreamingCloudFetchProvider { } _ => { debug!( - "Link for chunk {} missing or expired; \ - triggering batched refresh", - chunk_index + "Link for chunk {} {}; triggering batched refresh", + chunk_index, + if rejected_url.is_some() { + "rejected by storage" + } else { + "missing or expired" + } ); // Bound the refresh RPC by the remaining chunk // budget so a stalled refresh can't overshoot the @@ -2159,7 +2163,8 @@ mod tests { use wiremock::matchers::method; use wiremock::{Mock, MockServer, ResponseTemplate}; - const RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(500); + // Long enough that the < 2 × delay bound leaves a wide margin for the round-trips. + const RETRY_DELAY: std::time::Duration = std::time::Duration::from_secs(1); // Storage refuses every URL, including refreshed ones. let server = MockServer::start().await; From 70f94d451b77c73310f4db0e9ce2a7d0bbe5d88f Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 10:19:21 +0000 Subject: [PATCH 05/11] test(cloudfetch): cover the refresh waiter with a rejected link Review follow-up: a waiter whose cached link is unexpired but rejected must still refresh after another task's refresh skips its chunk. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- src/reader/cloudfetch/streaming_provider.rs | 48 +++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index a69c5d49..57ab3069 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -3243,6 +3243,54 @@ mod tests { ); } + #[tokio::test] + async fn refresh_waiter_does_not_take_a_rejected_link_as_fresh() { + // Chunk 0's link has not expired, but storage rejected its URL. Another + // task holds the refresh claim and finishes without touching chunk 0, so + // the waiter must still issue its own refresh instead of skipping it. + let rejected = create_test_link(0); + let chunks: Arc> = Arc::new(DashMap::new()); + chunks.insert( + 0, + entry_with_state(rejected.clone(), ChunkState::Downloading), + ); + let mock = RefreshCountingMock::new(1); + let coordinator = Arc::new(RefreshCoordinator::default()); + coordinator.in_progress.store(true, Ordering::Release); + + let fetcher: Arc = mock.clone(); + let (task_chunks, task_coordinator) = (Arc::clone(&chunks), Arc::clone(&coordinator)); + let rejected_url = rejected.url.clone(); + let waiter = tokio::spawn(async move { + StreamingCloudFetchProvider::refresh_links_batch_replacing( + 0, + Some(&rejected_url), + &fetcher, + &task_chunks, + &task_coordinator, + &CancellationToken::new(), + None, + ) + .await + }); + // On the single-threaded test runtime this sleep lets the waiter park on `done`. + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + assert!( + !waiter.is_finished(), + "the waiter must wait for the other refresh" + ); + coordinator.in_progress.store(false, Ordering::Release); + coordinator.done.notify_waiters(); + + waiter.await.unwrap().unwrap(); + assert_eq!(mock.refresh_calls.load(AtomicOrdering::SeqCst), 1); + assert_ne!( + chunks.get(&0).unwrap().link.as_ref().unwrap().url, + rejected.url, + "the rejected URL must be replaced" + ); + } + #[tokio::test] async fn refresh_batch_disjoint_window_loser_retries_claim() { // Loser-of-claim disjoint-window gap (round-3 follow-up): From c6df575d53db3083e16841f15e0fcf9336728693 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sun, 15 Nov 2026 07:31:10 +0000 Subject: [PATCH 06/11] test(cloudfetch): cover a refused URL that another task already replaced Review follow-up. A refresh for a refused URL is skipped when the cached link already carries a different, fresh URL; the new test fails if any refusal is treated as stale. The waiter test parks the waiter with a yield instead of a 50ms sleep, and the download_chunk_with_retry doc names the refusal path. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- src/reader/cloudfetch/streaming_provider.rs | 41 +++++++++++++++++++-- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index 57ab3069..6e8ef1bc 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -927,8 +927,9 @@ impl StreamingCloudFetchProvider { )) } - /// Download a single chunk with retry and link refresh on expiry, - /// bounded end-to-end by [`CloudFetchConfig::download_timeout`]. + /// Download a single chunk with retry, refreshing the link when it expires + /// or storage refuses it (401/403/404), bounded end-to-end by + /// [`CloudFetchConfig::download_timeout`]. async fn download_chunk_with_retry( chunk_index: i64, ctx: &DownloadCtx, @@ -3273,8 +3274,8 @@ mod tests { ) .await }); - // On the single-threaded test runtime this sleep lets the waiter park on `done`. - tokio::time::sleep(std::time::Duration::from_millis(50)).await; + // On the single-threaded test runtime one yield runs the waiter until it parks on `done`. + tokio::task::yield_now().await; assert!( !waiter.is_finished(), "the waiter must wait for the other refresh" @@ -3291,6 +3292,38 @@ mod tests { ); } + #[tokio::test] + async fn refresh_skips_a_rejected_url_another_task_already_replaced() { + // Storage refused chunk 0's original URL, but another task has already + // cached a fresh one, so no refresh RPC is needed. + let rejected = create_test_link(0); + let replaced = RefreshCountingMock::fresh_link(0); + let chunks: Arc> = Arc::new(DashMap::new()); + chunks.insert( + 0, + entry_with_state(replaced.clone(), ChunkState::Downloading), + ); + let mock = RefreshCountingMock::new(1); + let fetcher: Arc = mock.clone(); + + StreamingCloudFetchProvider::refresh_links_batch_replacing( + 0, + Some(&rejected.url), + &fetcher, + &chunks, + &Arc::new(RefreshCoordinator::default()), + &CancellationToken::new(), + None, + ) + .await + .unwrap(); + assert_eq!(mock.refresh_calls.load(AtomicOrdering::SeqCst), 0); + assert_eq!( + chunks.get(&0).unwrap().link.as_ref().unwrap().url, + replaced.url + ); + } + #[tokio::test] async fn refresh_batch_disjoint_window_loser_retries_claim() { // Loser-of-claim disjoint-window gap (round-3 follow-up): From 274c83d151584ad17eb9ae728e83f64f1b07bc7a Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sun, 15 Nov 2026 07:48:59 +0000 Subject: [PATCH 07/11] test(cloudfetch): pin a failed refresh after a refused download Review follow-up. A refused download whose refresh RPC fails surfaces the refresh error after one download; the RPC retries transient errors itself, so the outer loop does not stack a second budget on it. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- src/reader/cloudfetch/streaming_provider.rs | 85 +++++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index 6e8ef1bc..a3a17f2e 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -2253,6 +2253,91 @@ mod tests { ); } + #[tokio::test] + async fn refused_url_with_failing_refresh_surfaces_the_refresh_error() { + use crate::client::retry::{build_retry_configs, RetryConfig}; + use crate::client::{DatabricksHttpClient, HttpClientConfig}; + use crate::types::sea::CompressionCodec; + use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; + use wiremock::matchers::method; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + // The refresh RPC retries transient errors itself, so an error it + // returns is final for this chunk: no further download of the refused URL. + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(403)) + .mount(&server) + .await; + + #[derive(Debug)] + struct FailingFetcher { + refresh_calls: AtomicUsize, + } + + #[async_trait::async_trait] + impl ChunkLinkFetcher for FailingFetcher { + async fn fetch_links(&self, _: i64, _: i64) -> Result { + unreachable!() + } + + async fn refetch_link(&self, _: i64, _: i64) -> Result { + unreachable!() + } + + async fn refetch_links_from(&self, _: i64, _: i64) -> Result> { + self.refresh_calls.fetch_add(1, AtomicOrdering::SeqCst); + Err(Error::unavailable().message("refresh RPC down")) + } + } + + let retry = RetryConfig { + max_retries: 0, + ..RetryConfig::default() + }; + let http_client = Arc::new( + DatabricksHttpClient::new( + HttpClientConfig::default(), + build_retry_configs(&retry, &HashMap::new()), + ) + .unwrap(), + ); + let fetcher = Arc::new(FailingFetcher { + refresh_calls: AtomicUsize::new(0), + }); + let chunks = Arc::new(DashMap::new()); + let original = CloudFetchLink { + url: format!("{}/chunk-0.arrow", server.uri()), + ..create_test_link(0) + }; + chunks.insert(0, entry_with_state(original, ChunkState::Downloading)); + let ctx = DownloadCtx { + downloader: Arc::new(ChunkDownloader::new( + http_client, + CompressionCodec::None, + 0.1, + )), + link_fetcher: fetcher.clone(), + chunks, + refresh_coordinator: Arc::new(RefreshCoordinator::default()), + cancel_token: CancellationToken::new(), + statement_id: None, + metrics: Arc::new(CloudFetchMetrics::new(Some(1))), + max_retries: 3, + retry_delay: std::time::Duration::ZERO, + download_timeout: std::time::Duration::ZERO, + }; + + let error = StreamingCloudFetchProvider::download_chunk_with_retry(0, &ctx) + .await + .expect_err("a refused URL whose refresh fails must fail"); + assert_eq!(error.message, "Link refresh RPC failed for chunk 0"); + let cause = error.cause.expect("the refresh error is the cause"); + assert_eq!(cause.message, "refresh RPC down"); + assert_eq!(fetcher.refresh_calls.load(AtomicOrdering::SeqCst), 1); + assert_eq!(server.received_requests().await.unwrap().len(), 1); + } + // ─── End-to-end download deadline (issue #321 / audit H05) ─────────── // // These tests exercise `download_chunk_with_retry`'s absolute From cb4b6acaefbfaf118d1eac87d821e0091775a436 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sun, 15 Nov 2026 08:17:48 +0000 Subject: [PATCH 08/11] fix(cloudfetch): warn when storage refuses a download Review follow-up. The first 401/403/404 refusal now logs at warn with the attempt count and error, like every other failed attempt; before, it skipped the shared retry warning and only showed at debug. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- napi/index.d.ts | 1821 ++++++++++--------- napi/index.js | 918 +++++++--- src/reader/cloudfetch/streaming_provider.rs | 10 +- 3 files changed, 1585 insertions(+), 1164 deletions(-) diff --git a/napi/index.d.ts b/napi/index.d.ts index bcb54502..1f1d3581 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -1,362 +1,806 @@ -/* tslint:disable */ -/* eslint-disable */ - /* auto-generated by NAPI-RS */ - +/* eslint-disable */ /** - * Per-statement options for `Connection.executeStatement`. - * - * Mirrors the kernel `StatementSpec` knobs that are safe to thread - * through napi without a kernel-side change. Today this covers: - * - `statementConf` — per-statement Spark conf overlay - * (`StatementSpec.statement_conf` → SEA `parameters` / - * Thrift `confOverlay`) - * - `queryTags` — convenience wrapper over `statementConf` with - * key `query_tags`; serialised to the same comma-separated - * `key:value` wire shape NodeJS Thrift's `serializeQueryTags` - * produces (`lib/utils/queryTags.ts`). Backslashes in keys are - * doubled; backslash/colon/comma in values are backslash-escaped. + * Opaque result-fetch handle returned by + * `AsyncStatement.awaitResult()`. Wraps a kernel `ResultStream` + * directly; structurally analogous to the sync `Statement`'s + * fetch-side surface (`fetchNextBatch` / `schema` / + * `statementId`). * - * `rowLimit` (SEA `row_limit`) is exposed here and threaded onto the kernel - * `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`) - * carry bound query parameters, decoded via `params::parse_typed_value`. - * `rawParams` forwards pre-marshalled SEA parameters unchanged. - * (There is no `queryTimeoutSecs`: it abused the SEA `wait_timeout` inline-hold - * window and was removed — a real per-statement timeout is `STATEMENT_TIMEOUT`.) + * `cancel()` / `close()` are not exposed: the parent + * `AsyncStatement` owns server-side lifecycle. A `close()` here + * would create dual-ownership of the same statement_id with + * inconsistent close semantics. Callers `close()` the parent + * `AsyncStatement` after they're done fetching. * - * **Tag-order caveat (M4 parity note).** The napi `queryTags` field - * is a Rust `HashMap` whose iteration order is - * non-deterministic, so the serialised `query_tags` value may have - * a different key order than Thrift's `serializeQueryTags` (which - * iterates `Object.keys(...)` in insertion order) for the same - * input. The SEA server is order-insensitive on conf values, so - * the two are functionally equivalent. If a caller needs - * byte-identical Thrift parity, the JS adapter pre-serialises via - * `serializeQueryTags` and writes the result into - * `statementConf["query_tags"]` directly — see - * `KernelSessionBackend.executeStatement` in the NodeJS driver. This - * path is the one the production code uses. + * Schema is cached at construction so it survives the underlying + * stream being drained; mirrors the sync `Statement.schema()` + * post-close contract. */ -export interface ExecuteOptions { +export declare class AsyncResultHandle { /** - * Per-statement Spark conf overlay. Merged on top of the - * session-level `sessionConf` at execute time; this map wins - * on key collisions. Unknown keys are rejected by the server. + * Server-issued statement id. Cached at construction; readable + * for log correlation. Matches the parent `AsyncStatement`'s + * `statementId`. */ - statementConf?: Record + get statementId(): string /** - * Query tags as key→value pairs. Serialised to a comma- - * separated `key:value` string (backslash-escaping `\`, `:`, - * `,`) and placed into `statementConf["query_tags"]`, matching - * NodeJS Thrift's `serializeQueryTags` wire shape. Passing - * both `queryTags` AND a `query_tags` key in `statementConf` - * raises `InvalidArgument` — the caller's intent is ambiguous - * so we refuse to silently pick one over the other. - * - * A **`null`** value emits a **bare key** (no colon) — e.g. - * `{ production: null }` → `"production"` — matching the - * connectors' `key`-only tag form. - * - * See the struct-level "Tag-order caveat" for the - * HashMap-iteration-order vs `Object.keys`-iteration-order - * divergence and the byte-identical-Thrift-parity workaround. + * Pull the next batch of results. Returns `null` when the + * stream is exhausted. The returned `ArrowBatch.ipcBytes` is a + * complete Arrow IPC stream (schema header + 1 record-batch + * message), suitable for handing to `apache-arrow`'s + * `RecordBatchReader`. Byte-identical to the sync + * `Statement.fetchNextBatch()` payload for the same query. */ - queryTags?: Record + fetchNextBatch(): Promise /** - * Server-side cap on the number of rows this statement returns - * (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to - * `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. + * Result schema as an Arrow IPC payload (schema header only, + * no record-batch message). Available before any batches have + * been fetched. Sync because the body has no `.await` — + * `encode_ipc_stream` is pure CPU work over the cached + * `Arc`. */ - rowLimit?: number + schema(): ArrowSchema +} + +/** + * Opaque async-statement handle. + * + * Returned by `Connection.submitStatement(...)` after the kernel + * `Statement::submit()` returns (server sent `wait_timeout=0s`, so + * the response carries a `statement_id` but the statement is still + * `Pending`/`Running`). JS drives polling via `status()` / + * `awaitResult()`. + * + * Concurrency shape: `status()`, `awaitResult()`, and `close()` take + * `inner.lock()` and hold the guard across the kernel `.await` (tokio + * `Mutex` is FIFO), so `status()` / `close()` queue behind any + * in-flight `awaitResult()` until it returns naturally. `cancel()` is + * the deliberate exception: it does **not** touch `inner` — it fires + * through the detached `AsyncStatementCanceller` (session + + * statement_id, captured at construction), so an explicit + * `stmt.cancel()` interrupts an in-flight `awaitResult()` instead of + * queueing behind it. The server-side cancel flips the statement + * terminal, which the parked `awaitResult()` poll loop observes + * (`Cancelled`) and returns on. The kernel's `AwaitResultCancelGuard` + * still covers the drop-cancel case (Promise.race / timeout) + * independently — see module docs. + */ +export declare class AsyncStatement { /** - * Positional parameters, in 1-based wire order. Index `i` in this - * Vec corresponds to the `i+1`-th `?` placeholder in the SQL. - * Each entry is a `{ sqlType, value }` pair — `value` is the - * string-encoded literal or `null` for SQL NULL. Mirrors - * `StatementSpec::positional_params`; decoded via [`parse_typed_value`]. + * Server-issued statement id. Cached at construction; readable + * even after `close()` so JS-side log lines can correlate + * against kernel / server logs which key on the same id. */ - positionalParams?: Array + get statementId(): string /** - * Named parameters (`:name` placeholders). Each carries its `name` - * alongside the `{ sqlType, value? }` pair. Mapped to a kernel - * `TypedValue` via the same [`parse_typed_value`] codec and bound with - * `StatementSpec::param_named`. Named is the SEA-spec-required public - * param form (`StatementParameter.name` is `openapi_required`); - * positional is the documented-undocumented variant. The two are - * mutually exclusive at the SQL level (`?` vs `:name`). + * One-shot status check. Returns a string enum matching the + * kernel `StatementStatus` shape: + * `'Pending' | 'Running' | 'Succeeded' | 'Failed' | + * 'Cancelled' | 'Closed' | 'Unknown'`. (`'Unknown'` is the + * `#[non_exhaustive]` forward-compat catch-all that + * `StatementStatus::as_str` can return — consumers switching on + * the state must handle it.) Returns + * `KernelError(InvalidStatementHandle)` if the statement has + * been explicitly `close()`d. + * + * The `Failed` variant collapses to the string `'Failed'` on + * the JS side; the underlying error envelope (sql_state / + * error_code / query_id) is surfaced by `awaitResult()`'s + * rejection, which is where callers actually need the typed + * error. `status()` is intended for polling progress UIs + * that only need the state name. */ - namedParams?: Array + status(): Promise + /** Rows modified by the statement (UPDATE / INSERT / DELETE / MERGE). */ + numModifiedRows(): Promise /** - * Pre-marshalled parameters passed through `StatementSpec::param_raw`. - * Omit `name` for positional values. Raw parameters cannot be mixed with - * typed parameters or combine named and positional markers. + * Server-supplied user-facing message (may contain SQL fragments — + * redact before centralised logging). */ - rawParams?: Array -} -/** - * A named bound parameter — a [`TypedValueInput`] plus its `:name`. Kept a - * distinct napi object (rather than an optional `name` on `TypedValueInput`) - * so the positional surface stays a clean ordered list with no name field. - */ -export interface NamedTypedValueInput { - name: string - sqlType: string - value?: string -} -/** - * Authentication mode selector crossing the napi boundary. The string - * literals are what napi-rs emits from this `#[napi(string_enum)]` — the - * NodeJS SEA adapter (`KernelAuth`) matches them verbatim (`'Pat'`, - * `'OAuthM2m'`, `'OAuthU2m'`, `'AzureSpM2m'`). - * - * Mirrors the kernel [`AuthConfig`] variants this binding supports. - * `OAuthFederation` / `External` are intentionally not exposed yet — the - * kernel marks federation as not-yet-implemented and `External` is a - * Rust-trait escape hatch with no JS-callback bridge. - */ -export const enum AuthMode { - /** Personal access token (`token`). */ - Pat = 'Pat', - /** OAuth 2.0 machine-to-machine — `oauthClientId` + `oauthClientSecret`. */ - OAuthM2m = 'OAuthM2m', + displayMessage(): Promise + /** Server-supplied diagnostic detail. */ + diagnosticInfo(): Promise + /** Server-supplied structured error detail (JSON), when enabled. */ + errorDetailsJson(): Promise /** - * OAuth 2.0 machine-to-machine with a JWT private-key client - * assertion — `oauthClientId` + `jwtKeyFile` + `jwtKid`. + * Block until the server reaches a terminal state, then return + * an `AsyncResultHandle` that wraps the materialised result + * stream. The handle exposes `fetchNextBatch()` / `schema()` + * for consuming the result, plus `statementId` for log + * correlation. + * + * Drop-cancel safety: kernel `await_result` installs + * `AwaitResultCancelGuard` which fires a fire-and-forget + * `cancel_statement` if the future is dropped mid-poll + * (timeout, tokio::select! loser, JS-side `Promise.race` + * loser). The `util::guarded` `catch_unwind` here covers the + * V8-panic-across-boundary case on top. Returns + * `KernelError(InvalidStatementHandle)` if the statement has + * been explicitly `close()`d. */ - OAuthM2mJwt = 'OAuthM2mJwt', + awaitResult(): Promise /** - * OAuth 2.0 user-to-machine (browser flow) — optional `oauthClientId` - * + `oauthRedirectPort`. + * Server-side cancel. Returns + * `KernelError(InvalidStatementHandle)` if the statement has + * been explicitly `close()`d. Idempotent against a server + * that already reached a terminal state — the kernel's + * `cancel_statement` is a no-op there. + * + * **Lock-free by design.** Unlike `status()` / `awaitResult()` / + * `close()`, this does not take `inner.lock()` — it fires through + * the detached `AsyncStatementCanceller` captured at construction. + * That lets `stmt.cancel()` interrupt an in-flight `awaitResult()` + * (which holds the mutex for the whole poll) instead of queueing + * behind it: the server-side cancel flips the statement terminal, + * the parked `awaitResult()` poll loop observes `Cancelled` and + * returns. The closed-state check reads a lock-free flag so a + * cancel after an explicit `close()` still surfaces + * `InvalidStatementHandle`. */ - OAuthU2m = 'OAuthU2m', + cancel(): Promise /** - * Azure Entra service-principal M2M — `azureClientId` + - * `azureClientSecret` (+ optional `azureTenantId` / - * `azureWorkspaceResourceId`). The kernel builds the Entra token - * endpoint + `.default` scope, auto-discovers the tenant from the - * workspace when `azureTenantId` is omitted, and — when - * `azureWorkspaceResourceId` is set — additionally sends the SP - * management token for an RBAC-only service principal. + * Explicit close. Idempotent — a second call on an + * already-closed handle returns `Ok(())`. On `Err`, the napi + * inner is already `None`, so a JS-side retry sees the + * closed-handle short-circuit and returns `Ok(())` without + * re-attempting the wire call. The kernel's own `Drop` + * fire-and-forget retry runs once in the background. */ - AzureSpM2m = 'AzureSpM2m' + close(): Promise } + /** - * A single extra HTTP header as an explicit `{ name, value }` pair. + * Handle returned by `Connection.executeStatementCancellable`. Owns the + * built-but-not-yet-executed kernel `Statement` plus a detached + * [`StatementCanceller`] captured before dispatch, so JS can fire a + * server-side cancel while the blocking `result()` is in flight. * - * An ordered list of these (`ConnectionOptions.custom_headers`) mirrors - * the kernel core's `Vec<(String, String)>` and the pyo3 binding's - * `http_headers`: order is preserved and duplicate `name`s are allowed. - * A struct (rather than a raw `[name, value]` tuple) because napi-rs - * does not marshal Rust tuples through `#[napi(object)]` fields; the - * struct is the idiomatic, self-documenting equivalent and maps to a JS - * `{ name: string, value: string }`. - */ -export interface HeaderEntry { - name: string - value: string -} -/** - * Programmatic HTTP/HTTPS proxy configuration, mirroring the kernel's - * internal [`ProxyConfig`]. Supplied as a structured object rather than a - * flattened URL so credentials never have to be percent-encoded into the URL - * and the bypass-host list can be expressed. - * - * - `url` — proxy endpoint, e.g. `"http://proxy.corp.example.com:8080"`. Must - * use the `http://` or `https://` scheme. - * - `username` / `password` — optional proxy basic-auth, applied via - * `reqwest`'s `Proxy::basic_auth` (not embedded in the URL). - * - `bypassHosts` — optional comma-separated host/domain list that should - * bypass the proxy (e.g. `"localhost,*.internal.corp"`). + * `pending` is `Arc>>` so `result()` can + * `.take()` the statement (the kernel `execute()` borrows it `&mut`, + * then it moves into the produced `Statement` wrapper to keep its + * `ValidityFlag` set — see `statement.rs`). A second `result()` call + * after the first resolved surfaces `InvalidStatementHandle`. */ -export interface ProxyInput { - url: string - username?: string - password?: string - bypassHosts?: string +export declare class CancellableExecution { + /** + * The server-issued statement id this execution targets, if the + * server has issued one yet (`null` before the initial submit + * round-trip publishes it mid-`result()`). Useful for log + * correlation while the blocking drive is in flight. + */ + get statementId(): string | null + /** + * Drive the blocking `execute()` and resolve to a `Statement` + * (identical to what `executeStatement` returns) once the kernel + * reaches a terminal state and the result stream is ready. + * + * Consumes the pending statement: a second `result()` call returns + * `KernelError(InvalidStatementHandle)`. The future is + * drop-cancel-safe — the kernel's per-execute `MidExecuteCancelState` + * guard fires a fire-and-forget `cancel_statement` if this future is + * dropped mid-flight (`Promise.race` / timeout loser), independently + * of an explicit `cancel()`. + * + * On a server-side cancel the kernel's blocking `execute()` currently + * surfaces `InvalidArgument` (a known kernel quirk — the async path + * returns `Cancelled`). When this handle's `cancel()` actually dispatched a + * server-side cancel, we normalise that into `Cancelled` here so JS callers + * can rely on a single cancelled-status code regardless of execution path. + * + * Three outcomes can race the blocking drive: (1) a natural terminal state + * → `Ok` or the genuine error; (2) an explicit `cancel()` that dispatched a + * server cancel → this `result()` rejects with a `Cancelled`-coded error + * (the normalisation above); (3) the future being **dropped** mid-flight + * (`Promise.race`/timeout loser) → the kernel's `MidExecuteCancelState` + * drop-guard fires a fire-and-forget `cancel_statement`, but there is no + * `result()` left to observe a code. Only (2) yields a `Cancelled` error. + */ + result(): Promise + /** + * Server-side cancel of the in-flight statement. + * + * Lock-free: fires the detached `StatementCanceller` captured at + * construction rather than taking the mutex `result()` holds, so it + * interrupts a still-running blocking `result()` instead of queueing + * behind it. No-op (returns `Ok`) if `result()` already finished + * successfully, or if no statement id has been observed yet (query still + * in its initial submit round-trip), and idempotent against a server + * already in a terminal state. + */ + cancel(): Promise } + /** - * JS-visible options for opening a Databricks SQL session. + * Opaque connection handle wrapping a kernel `Session`. * - * Authentication is selected by `authMode` (default [`AuthMode::Pat`]): - * - `Pat` — `token` required. - * - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required. - * - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional - * (defaults to the `databricks-sql-connector` client on port 8030). - * - `AzureSpM2m` — `azureClientId` + `azureClientSecret` required - * (+ optional `azureTenantId` / `azureWorkspaceResourceId`). + * `inner` is `Arc>>` so: + * - the Drop impl can clone the `Arc` and `.take()` the session on a + * background tokio task without holding `&mut self` (which Drop is + * forbidden from doing across an `await`), + * - `close()` can `.take()` the session to consume it for the kernel's + * move-by-value `Session::close(self)` signature. * - * Catalog / schema / sessionConf are applied once at session creation - * and remain in effect for every statement run on the resulting - * `Connection`. The SEA wire protocol carries them on - * `CreateSession`, not on `ExecuteStatement` — so there is no - * per-statement override path on this binding. + * **Concurrency shape** — both `executeStatement` and + * `submitStatement` build the kernel `Statement` under `inner.lock()` + * and then RELEASE the guard before the wire call + * (`stmt.execute().await` / `stmt.submit().await`). `Session::statement()` + * is `&self`-callable and only clones the session's internal `Arc`, so + * the built statement is independent of the guard. Concurrent + * `Promise.all([executeStatement(q1), submitStatement(q2)])` therefore + * serialise only for the microsecond statement-build, not the network + * round-trip, and `close()` never blocks behind an in-flight execute or + * submit. See + * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. */ -export interface ConnectionOptions { +export declare class Connection { /** - * Workspace host, e.g. `adb-…azuredatabricks.net`. The kernel - * normalises this — bare hostnames get `https://` prepended. + * Server-issued session id. Cached at construction; readable + * even after `close()` so JS-side log lines can correlate + * against kernel / server logs which key on the same id. */ - hostName: string + get sessionId(): string /** - * JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The - * kernel parses out the warehouse id. + * Execute a SQL statement and return a Statement handle that + * streams batches via `fetchNextBatch()`. + * + * Catalog / schema / sessionConf are session-level + * (`openSession`). Per-statement options on `ExecuteOptions`: + * - `statementConf` — per-statement Spark conf overlay + * - `queryTags` — serialised to a comma-separated `key:value` + * string and placed in `statement_conf["query_tags"]`, + * matching NodeJS Thrift's `serializeQueryTags` wire shape + * + * `options` is omitted/`None` for the no-options path; passing + * `{ statementConf: {} }` (an empty map) is treated the same as + * omission to keep the wire shape stable for the common case. */ - httpPath: string + executeStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise /** - * Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat: - * existing PAT callers pass only `token`). + * directResults execute — the Thrift/JDBC model. Sends ExecuteStatement + * with no `wait_timeout` field (server applies its ~10s default inline wait + * and auto-closes on success) and returns WITHOUT polling past it: + * + * - a **`Statement`** (left arm) when the query finished within the inline + * wait — terminal, result ready inline, `close()` is a clean release; + * - an **`AsyncStatement`** (right arm) when it did not — a poll/cancel + * handle the caller drives (`status()` / `awaitResult()` / `cancel()`). + * + * JS distinguishes the arms by feature-detecting `awaitResult` (present + * only on `AsyncStatement`). This is the path that gives mid-run cancel for + * long queries WITHOUT the eager-handle / close-drives workaround: the + * returned handle always corresponds to a server-owned statement. + * + * **Load-bearing contract:** the kernel's `DirectStatement::{Completed, + * Running}` discriminant cannot ride on these opaque `#[napi]` classes, so + * consumers MUST feature-detect via `awaitResult` (the only member unique to + * `AsyncStatement`). `Statement` (the Completed arm) MUST NOT gain an + * `awaitResult` member, or every consumer silently misroutes. The pyo3 + * binding makes the same `await_result`-probe assumption. */ - authMode?: AuthMode + executeStatementDirect(sql: string, options?: ExecuteOptions | undefined | null): Promise /** - * Personal access token. Required (and non-empty) for - * [`AuthMode::Pat`]; ignored otherwise. + * Execute a SQL statement on the blocking (sync) path, but return a + * `CancellableExecution` handle so a concurrent JS task can cancel + * the query *while it is still running server-side*. + * + * `executeStatement` builds the kernel `Statement`, awaits the + * blocking `execute()`, and only then hands JS a `Statement` — so a + * query that runs for several seconds is uncancellable from JS on + * that path (there is no handle until the blocking call resolves). + * This method instead builds the statement, captures a detached + * `StatementCanceller` **before** dispatching `execute()`, and hands + * JS a `CancellableExecution` immediately. The caller drives the + * blocking execution via `result()` (resolves to the same + * `Statement` `executeStatement` returns) and can fire `cancel()` + * concurrently to interrupt a still-running query mid-COMPUTE. + * + * Option semantics are identical to `executeStatement`. + * Mirrors the pyo3 `Statement.canceller()` / `Statement.execute()` + * split (PR #121): obtain the canceller before the blocking drive. */ - token?: string + executeStatementCancellable(sql: string, options?: ExecuteOptions | undefined | null): Promise /** - * OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for - * [`AuthMode::OAuthU2m`] (defaults to `databricks-sql-connector`). + * Submit a SQL statement and return immediately with an + * `AsyncStatement` handle, without blocking until the query + * finishes. The kernel's `Statement::submit()` sends + * `wait_timeout=0s`, so the server responds as soon as it has a + * `statement_id` (state `Pending`/`Running`); JS drives polling + * via `AsyncStatement.status()` and materialises results with + * `AsyncStatement.awaitResult()`. + * + * This is the async-execution path the Thrift backend always + * uses (`runAsync: true`): the SEA backend submits, returns a + * pending operation handle, and polls to terminal during + * fetch. Option semantics (statementConf / queryTags / + * rowLimit / positional + named params) match `executeStatement`. + * Submit always sends `wait_timeout=0s` so the call returns + * immediately; the caller drives completion via `status()` / + * `awaitResult()`. Only the blocking-vs-pending return contract + * differs from `executeStatement`. */ - oauthClientId?: string - /** OAuth client secret. Required for [`AuthMode::OAuthM2m`]. */ - oauthClientSecret?: string + submitStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise /** - * Localhost callback port for the [`AuthMode::OAuthU2m`] browser - * flow. Omitted ⇒ kernel default (8030). + * Explicit close. Awaits the server-side `DeleteSession` so the + * JS caller can observe failures (auth revoked mid-session, + * warehouse stopped, network error). Idempotent — a second call + * on an already-closed connection returns `Ok`. + * + * **Errors are terminal from the JS side.** The kernel session + * handle is consumed (`take()`) BEFORE the wire `DeleteSession` + * runs, because `Session::close` takes `self` by value. On `Err`, + * the napi `inner` is already `None`, so a JS-side retry sees a + * closed connection and returns `Ok(())` without re-attempting + * the wire call. The kernel's own `Drop` fire-and-forget retry + * runs once in the background — the JS caller can log the error + * but cannot drive a retry. If you need retry-on-failure + * semantics for `DeleteSession`, layer them above this method. */ - oauthRedirectPort?: number + close(): Promise /** - * OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults - * (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M). + * All catalogs visible to the session. + * + * JDBC `getCatalogs` shape: `TABLE_CAT: Utf8`. */ - oauthScopes?: Array + listCatalogs(): Promise /** - * OAuth token endpoint override. When omitted the kernel discovers the - * endpoint via the workspace's OIDC configuration. Set it to point the - * client-credentials / JWT client-assertion grant at the workspace's - * configured IdP token endpoint (e.g. Entra ID for Azure Databricks), - * which is required when that IdP — not Databricks-native OIDC — is the - * authority for [`AuthMode::OAuthM2m`] / [`AuthMode::OAuthM2mJwt`]. + * Schemas filtered by catalog (exact) and schema name pattern. An empty + * catalog matches nothing; non-empty catalogs remain exact identifiers. + * + * JDBC `getSchemas` shape: `TABLE_SCHEM, TABLE_CATALOG`. */ - tokenUrl?: string + listSchemas(catalog?: string | undefined | null, schemaPattern?: string | undefined | null): Promise /** - * U2M on-disk token-cache control (kernel path). Omitted ⇒ the kernel - * default (cache enabled, encrypted under a machine-local key, survives - * restarts). `false` disables on-disk persistence (re-login each fresh - * process); `true` keeps it enabled. Applies to [`AuthMode::OAuthU2m`]. + * Tables filtered by catalog (**pattern**), schema (pattern), table + * (pattern). + * + * The catalog is an ODBC/JDBC LIKE pattern (`%` / `_`), matching + * Thrift `getTables`: a wildcard catalog matches multiple catalogs; + * a literal name (or an escaped `\_` / `\%`) takes the fast exact + * path. `undefined`/omitted catalog means "all catalogs", while an + * **empty string** means "match nothing" (zero rows) — pass + * `undefined`, not `""`, for all catalogs. The catalog pattern is + * validated (whitespace-only / NUL / >255 bytes are rejected with an + * error). + * + * JDBC `getTables` shape: 10 columns. `tableTypes`, when provided, + * filters rows by `TABLE_TYPE` kernel-side. + * + * `tableTypes` is an advisory filter. Databricks `SHOW TABLES` does + * NOT honour the table-type filter server-side; the kernel applies + * it client-side after the result returns. Callers expecting + * server-side rejection of off-type tables should not rely on this. */ - tokenCacheEnabled?: boolean + listTables(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, tableTypes?: Array | undefined | null): Promise /** - * Optional passphrase for the U2M on-disk token cache (AES-256 key). - * Omitted/blank ⇒ a machine-local derived key. Supplying one is stronger. - * A passphrase with no explicit `tokenCacheEnabled` implies enabled. - * Applies to [`AuthMode::OAuthU2m`]. - */ - tokenCachePassphrase?: string + * Columns of tables matching the filter. An empty catalog matches + * nothing; non-empty catalogs remain exact identifiers. + * + * JDBC `getColumns` shape: 23 columns. + */ + listColumns(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, columnPattern?: string | undefined | null): Promise /** - * Path to the PEM private-key file. Required for - * [`AuthMode::OAuthM2mJwt`]. + * Functions visible to the session. An empty `catalog` is forwarded to + * SEA for native `GetFunctions`; `schemaPattern` and `functionPattern` are SQL LIKE. */ - jwtKeyFile?: string - /** JWT key id (`kid`). Required for [`AuthMode::OAuthM2mJwt`]. */ - jwtKid?: string + listFunctions(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, functionPattern?: string | undefined | null): Promise /** - * Passphrase for an encrypted PKCS#8 key. Optional for - * [`AuthMode::OAuthM2mJwt`] (omit for an unencrypted key). + * Procedures visible to the session. `catalog` is exact; + * `schemaPattern` and `procedurePattern` are SQL LIKE. */ - jwtPassphrase?: string + listProcedures(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, procedurePattern?: string | undefined | null): Promise /** - * JWT signing algorithm (`RS256`/`384`/`512`, `PS256`/`384`/`512`, - * `ES256`, `ES384`). Optional for [`AuthMode::OAuthM2mJwt`] - * (omitted ⇒ kernel default `RS256`). + * All table types (`TABLE`, `VIEW`, `SYSTEM TABLE`, …). + * No wire call — static in-memory result. */ - jwtAlgorithm?: string + listTableTypes(): Promise /** - * SP-wide Workload Identity Federation client id used during mandatory - * token exchange. Omitted selects BYOT / account-wide WIF. + * SQL data types supported by the workspace. + * No wire call — static in-memory result. */ - identityFederationClientId?: string + listTypeInfo(): Promise /** - * Azure Entra app-registration client id. Required for - * [`AuthMode::AzureSpM2m`]; ignored otherwise. + * Primary keys for the given table. All three identifiers are + * exact — ODBC `SQLPrimaryKeys` does not support patterns. */ - azureClientId?: string + getPrimaryKeys(catalog: string | undefined | null, schema: string | undefined | null, table: string): Promise /** - * Azure Entra app-registration client secret. Required for - * [`AuthMode::AzureSpM2m`]. + * Foreign-key relationships. The parent side is optional. When the + * foreign table is omitted, returns an empty result without issuing a + * server statement. When it is provided, its catalog and schema are + * required. All identifiers are exact — no LIKE patterns. */ - azureClientSecret?: string + getCrossReference(parentCatalog?: string | undefined | null, parentSchema?: string | undefined | null, parentTable?: string | undefined | null, foreignCatalog?: string | undefined | null, foreignSchema?: string | undefined | null, foreignTable?: string | undefined | null): Promise +} + +/** + * Opaque executed-statement handle. + * + * **Current concurrency shape** — every method takes `inner.lock()` + * and holds the guard across the kernel `.await`. tokio `Mutex` is + * FIFO, so cancel/close queue behind any in-flight `fetchNextBatch` + * until it returns naturally. This is a known limitation that exists + * because the napi shape has not yet been split into an + * `Arc` (for cancel/close, which the + * kernel exposes as `&self`-callable) plus a `Mutex>` only + * for the borrowed-mut fetch path. The lock-shape refactor needs a + * small kernel-side accessor and lands in a follow-up PR — see + * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. + * + * `schema` and `statement_id` are cached at construction so they + * survive `close()` — JS callers building error reports against a + * disposed statement can still read them. + */ +export declare class Statement { /** - * Azure Entra tenant id. Optional for [`AuthMode::AzureSpM2m`]; - * omitted ⇒ the kernel auto-discovers it from the workspace's - * `/aad/auth` redirect (matching the Thrift connector). + * Server-issued statement id. Cached at construction; readable + * even after `close()` so JS-side log lines can correlate against + * kernel / server logs which key on the same id. */ - azureTenantId?: string + get statementId(): string /** - * Azure workspace ARM resource id. Optional for [`AuthMode::AzureSpM2m`]; - * when set the kernel also sends the SP management token - * (`X-Databricks-Azure-SP-Management-Token`) + the - * `X-Databricks-Azure-Workspace-Resource-Id` header, so a service - * principal with an Azure RBAC role but no workspace membership can - * authenticate. Omitted ⇒ the data token authenticates alone. + * Number of rows modified by the statement (UPDATE / INSERT / + * DELETE / MERGE). `null` for SELECT and on warehouses that don't + * surface the counter. Mirrors Thrift's + * `TGetOperationStatusResp.numModifiedRows`. */ - azureWorkspaceResourceId?: string + numModifiedRows(): Promise /** - * Default catalog for statements executed on this session. - * Routed through the kernel's `DefaultOpts` and onto the SEA - * `CreateSession.catalog` wire field. + * Server-supplied user-facing message. Mirrors Thrift's + * `TGetOperationStatusResp.displayMessage`. **PII / sensitive- + * data note:** may contain SQL fragments or parameter values — + * redact before centralised logging. + * + * Populated on `Succeeded` / `Closed` paths (incl. an empty `Closed`). + * On terminal-error states (`Failed` / `Cancelled`) the kernel returns + * an Error instead of a `Statement`, and the same field rides on the JS + * Error envelope under the same `displayMessage` key. */ - catalog?: string + displayMessage(): Promise /** - * Default schema for statements executed on this session. - * Routed through the kernel's `DefaultOpts` and onto the SEA - * `CreateSession.schema` wire field. + * Server-supplied diagnostic detail — multi-line operator / + * stack context. Mirrors Thrift's + * `TGetOperationStatusResp.diagnosticInfo`. For support surfaces, + * not user-facing. Same reachability + PII caveats as + * `displayMessage`. */ - schema?: string + diagnosticInfo(): Promise /** - * Server-bound session conf (Spark conf, `ANSI_MODE`, `TIMEZONE`, - * query-tag presets, …). Forwarded verbatim to SEA - * `session_confs`. Unknown keys are rejected server-side. + * Server-supplied JSON blob with extended error details. Mirrors + * Thrift's `TGetOperationStatusResp.errorDetailsJson`. + * Pass-through string — JS callers parse with `JSON.parse` if + * they need structured access. + * + * **Server-side gating:** populated only when the workspace has + * `spark.databricks.sql.errorDetailsJson.enabled = true` on the + * underlying SQL cluster. The flag is internal-only / default- + * false in the Databricks runtime, so for most JS callers this + * will return `null`. Admin-enabled workspaces return content + * shaped like `{"errorClass": "...", "messageTemplate": "..."}`. + * + * **Unbounded:** when populated, server can return a multi-MB + * blob; size before logging. */ - sessionConf?: Record + errorDetailsJson(): Promise /** - * Select whether `GEOMETRY` / `GEOGRAPHY` results use their native Arrow - * representation. `true` (the default) requests Arrow - * `struct` values; `false` requests WKT / EWKT - * in Arrow UTF-8 values. The kernel normalizes both standard-warehouse - * text and Reyden native Arrow results locally and never sends this choice - * to SEA. + * Pull the next batch of results. Returns `null` when the stream + * is exhausted. The returned `ArrowBatch.ipcBytes` is a complete + * Arrow IPC stream (schema header + 1 record-batch message) + * suitable for handing to `apache-arrow`'s `RecordBatchReader`. + * + * On `Err`, the stream is in an unspecified state — call + * `close()` and discard the `Statement`. Subsequent + * `fetchNextBatch()` calls after an error are not guaranteed to + * succeed or fail consistently. */ - enableGeoSpatialSupport?: boolean + fetchNextBatch(): Promise /** - * Driver name reported in telemetry system configuration. Omitted ⇒ - * kernel default. + * Result schema as an Arrow IPC payload (schema header only, no + * record-batch message). Available before any batches have been + * fetched, and remains available after `close()` — the kernel + * materialises the schema eagerly so JS callers can build error + * reports against a disposed statement. + * + * Sync because the body has no `.await` — `encode_ipc_stream` is + * pure CPU work over an `Arc` already cached on the + * wrapper. Mirrors `pyo3/src/statement.rs::arrow_schema` (sync). + * napi-rs converts a panic in a sync `#[napi]` entry point into a + * thrown JS error via its own macro-expanded boundary, so the + * `util::guarded` `catch_unwind` wrapper that the `async fn` + * entry points use is not required for this method. */ - driverName?: string + schema(): ArrowSchema /** - * Driver version reported in telemetry system configuration. Omitted ⇒ - * kernel default. + * Server-side cancel. + * + * For executed statements: short-circuits to `Ok(())` if + * `fetchNextBatch` has already returned `null` (stream + * naturally exhausted) — matches the JDBC `Statement.cancel()` + * no-op-after-completion contract, so JS callers can fire cancel + * defensively without distinguishing "real cancel" from "raced + * with natural completion." + * + * For metadata streams: no-op (the kernel has no in-flight + * cancellation surface for metadata calls today). + * + * Returns `KernelError(InvalidStatementHandle)` if the statement + * has been explicitly `close()`d. */ - driverVersion?: string + cancel(): Promise /** - * Runtime name reported in telemetry system configuration. Omitted ⇒ - * kernel default. + * Explicit close. + * + * For executed statements: awaits the server-side `CloseStatement` + * so the JS caller can observe failures (auth revoked mid-session, + * network error, server-side error). Idempotent — a second call + * on an already-closed statement returns `Ok`. + * + * **Errors are terminal from the JS side.** The kernel executed + * handle is taken out of `inner` BEFORE the wire `CloseStatement` + * runs (so `Drop` knows there's nothing left to clean up). On + * `Err`, the napi `inner` is already `None`, so a JS-side retry + * sees a closed statement and returns `Ok(())` without re- + * attempting the wire call. The kernel-level `ExecutedStatement` + * has been consumed at that point and the value is dropped on + * the way out of the closure — the kernel's `ExecutedStatement:: + * Drop` then fires-and-forgets a single retry on the captured + * runtime. The JS caller can log the error but cannot drive a + * further retry. If you need retry-on-failure semantics for + * `CloseStatement`, layer them above this method. + * + * For metadata streams: drops the stream (no server round-trip + * needed — metadata results have no in-flight server-side + * resource to release). */ - runtimeName?: string + close(): Promise +} + +/** + * A single Arrow IPC stream payload encoding one record batch (plus + * the schema header so the JS-side reader is stateless). + */ +export interface ArrowBatch { /** - * Runtime version reported in telemetry system configuration. Omitted ⇒ - * kernel default. + * Arrow IPC stream payload (schema header + 1 record-batch + * message). Decode with `apache-arrow`'s `RecordBatchReader`. */ - runtimeVersion?: string + ipcBytes: Buffer +} + +/** + * An Arrow IPC stream payload encoding just the result schema (no + * record-batch messages). Returned by `Statement.schema()`. + */ +export interface ArrowSchema { /** - * Runtime vendor reported in telemetry system configuration. Omitted ⇒ - * kernel default. + * Arrow IPC stream payload (schema header only, no record-batch + * messages). Decode with `apache-arrow`'s `RecordBatchReader` — + * the reader will expose the schema and immediately end. */ - runtimeVendor?: string + ipcBytes: Buffer +} + +/** + * Authentication mode selector crossing the napi boundary. The string + * literals are what napi-rs emits from this `#[napi(string_enum)]` — the + * NodeJS SEA adapter (`KernelAuth`) matches them verbatim (`'Pat'`, + * `'OAuthM2m'`, `'OAuthU2m'`, `'AzureSpM2m'`). + * + * Mirrors the kernel [`AuthConfig`] variants this binding supports. + * `OAuthFederation` / `External` are intentionally not exposed yet — the + * kernel marks federation as not-yet-implemented and `External` is a + * Rust-trait escape hatch with no JS-callback bridge. + */ +export declare const enum AuthMode { + /** Personal access token (`token`). */ + Pat = 'Pat', + /** OAuth 2.0 machine-to-machine — `oauthClientId` + `oauthClientSecret`. */ + OAuthM2m = 'OAuthM2m', /** - * Operating system name reported in telemetry system configuration. - * Omitted ⇒ kernel default. + * OAuth 2.0 machine-to-machine with a JWT private-key client + * assertion — `oauthClientId` + `jwtKeyFile` + `jwtKid`. */ - osName?: string + OAuthM2mJwt = 'OAuthM2mJwt', + /** + * OAuth 2.0 user-to-machine (browser flow) — optional `oauthClientId` + * + `oauthRedirectPort`. + */ + OAuthU2m = 'OAuthU2m', + /** + * Azure Entra service-principal M2M — `azureClientId` + + * `azureClientSecret` (+ optional `azureTenantId` / + * `azureWorkspaceResourceId`). The kernel builds the Entra token + * endpoint + `.default` scope, auto-discovers the tenant from the + * workspace when `azureTenantId` is omitted, and — when + * `azureWorkspaceResourceId` is set — additionally sends the SP + * management token for an RBAC-only service principal. + */ + AzureSpM2m = 'AzureSpM2m' +} + +/** + * JS-visible options for opening a Databricks SQL session. + * + * Authentication is selected by `authMode` (default [`AuthMode::Pat`]): + * - `Pat` — `token` required. + * - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required. + * - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional + * (defaults to the `databricks-sql-connector` client on port 8030). + * - `AzureSpM2m` — `azureClientId` + `azureClientSecret` required + * (+ optional `azureTenantId` / `azureWorkspaceResourceId`). + * + * Catalog / schema / sessionConf are applied once at session creation + * and remain in effect for every statement run on the resulting + * `Connection`. The SEA wire protocol carries them on + * `CreateSession`, not on `ExecuteStatement` — so there is no + * per-statement override path on this binding. + */ +export interface ConnectionOptions { + /** + * Workspace host, e.g. `adb-…azuredatabricks.net`. The kernel + * normalises this — bare hostnames get `https://` prepended. + */ + hostName: string + /** + * JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The + * kernel parses out the warehouse id. + */ + httpPath: string + /** + * Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat: + * existing PAT callers pass only `token`). + */ + authMode?: AuthMode + /** + * Personal access token. Required (and non-empty) for + * [`AuthMode::Pat`]; ignored otherwise. + */ + token?: string + /** + * OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for + * [`AuthMode::OAuthU2m`] (defaults to `databricks-sql-connector`). + */ + oauthClientId?: string + /** OAuth client secret. Required for [`AuthMode::OAuthM2m`]. */ + oauthClientSecret?: string + /** + * Localhost callback port for the [`AuthMode::OAuthU2m`] browser + * flow. Omitted ⇒ kernel default (8030). + */ + oauthRedirectPort?: number + /** + * OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults + * (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M). + */ + oauthScopes?: Array + /** + * OAuth token endpoint override. When omitted the kernel discovers the + * endpoint via the workspace's OIDC configuration. Set it to point the + * client-credentials / JWT client-assertion grant at the workspace's + * configured IdP token endpoint (e.g. Entra ID for Azure Databricks), + * which is required when that IdP — not Databricks-native OIDC — is the + * authority for [`AuthMode::OAuthM2m`] / [`AuthMode::OAuthM2mJwt`]. + */ + tokenUrl?: string + /** + * U2M on-disk token-cache control (kernel path). Omitted ⇒ the kernel + * default (cache enabled, encrypted under a machine-local key, survives + * restarts). `false` disables on-disk persistence (re-login each fresh + * process); `true` keeps it enabled. Applies to [`AuthMode::OAuthU2m`]. + */ + tokenCacheEnabled?: boolean + /** + * Optional passphrase for the U2M on-disk token cache (AES-256 key). + * Omitted/blank ⇒ a machine-local derived key. Supplying one is stronger. + * A passphrase with no explicit `tokenCacheEnabled` implies enabled. + * Applies to [`AuthMode::OAuthU2m`]. + */ + tokenCachePassphrase?: string + /** + * Path to the PEM private-key file. Required for + * [`AuthMode::OAuthM2mJwt`]. + */ + jwtKeyFile?: string + /** JWT key id (`kid`). Required for [`AuthMode::OAuthM2mJwt`]. */ + jwtKid?: string + /** + * Passphrase for an encrypted PKCS#8 key. Optional for + * [`AuthMode::OAuthM2mJwt`] (omit for an unencrypted key). + */ + jwtPassphrase?: string + /** + * JWT signing algorithm (`RS256`/`384`/`512`, `PS256`/`384`/`512`, + * `ES256`, `ES384`). Optional for [`AuthMode::OAuthM2mJwt`] + * (omitted ⇒ kernel default `RS256`). + */ + jwtAlgorithm?: string + /** + * SP-wide Workload Identity Federation client id used during mandatory + * token exchange. Omitted selects BYOT / account-wide WIF. + */ + identityFederationClientId?: string + /** + * Azure Entra app-registration client id. Required for + * [`AuthMode::AzureSpM2m`]; ignored otherwise. + */ + azureClientId?: string + /** + * Azure Entra app-registration client secret. Required for + * [`AuthMode::AzureSpM2m`]. + */ + azureClientSecret?: string + /** + * Azure Entra tenant id. Optional for [`AuthMode::AzureSpM2m`]; + * omitted ⇒ the kernel auto-discovers it from the workspace's + * `/aad/auth` redirect (matching the Thrift connector). + */ + azureTenantId?: string + /** + * Azure workspace ARM resource id. Optional for [`AuthMode::AzureSpM2m`]; + * when set the kernel also sends the SP management token + * (`X-Databricks-Azure-SP-Management-Token`) + the + * `X-Databricks-Azure-Workspace-Resource-Id` header, so a service + * principal with an Azure RBAC role but no workspace membership can + * authenticate. Omitted ⇒ the data token authenticates alone. + */ + azureWorkspaceResourceId?: string + /** + * Default catalog for statements executed on this session. + * Routed through the kernel's `DefaultOpts` and onto the SEA + * `CreateSession.catalog` wire field. + */ + catalog?: string + /** + * Default schema for statements executed on this session. + * Routed through the kernel's `DefaultOpts` and onto the SEA + * `CreateSession.schema` wire field. + */ + schema?: string + /** + * Server-bound session conf (Spark conf, `ANSI_MODE`, `TIMEZONE`, + * query-tag presets, …). Forwarded verbatim to SEA + * `session_confs`. Unknown keys are rejected server-side. + */ + sessionConf?: Record + /** + * Select whether `GEOMETRY` / `GEOGRAPHY` results use their native Arrow + * representation. `true` (the default) requests Arrow + * `struct` values; `false` requests WKT / EWKT + * in Arrow UTF-8 values. The kernel normalizes both standard-warehouse + * text and Reyden native Arrow results locally and never sends this choice + * to SEA. + */ + enableGeoSpatialSupport?: boolean + /** + * Driver name reported in telemetry system configuration. Omitted ⇒ + * kernel default. + */ + driverName?: string + /** + * Driver version reported in telemetry system configuration. Omitted ⇒ + * kernel default. + */ + driverVersion?: string + /** + * Runtime name reported in telemetry system configuration. Omitted ⇒ + * kernel default. + */ + runtimeName?: string + /** + * Runtime version reported in telemetry system configuration. Omitted ⇒ + * kernel default. + */ + runtimeVersion?: string + /** + * Runtime vendor reported in telemetry system configuration. Omitted ⇒ + * kernel default. + */ + runtimeVendor?: string + /** + * Operating system name reported in telemetry system configuration. + * Omitted ⇒ kernel default. + */ + osName?: string /** * Operating system version reported in telemetry system configuration. * Omitted ⇒ kernel default. @@ -514,9 +958,7 @@ export interface ConnectionOptions { * `User-Agent` entry here. */ customHeaders?: Array - /** - * Whether SEA API responses may use HTTP compression. Defaults to false. - */ + /** Whether SEA API responses may use HTTP compression. Defaults to false. */ seaResponseCompressionEnabled?: boolean /** * Retry/backoff tuning — all optional. An unset field keeps the kernel's @@ -547,10 +989,13 @@ export interface ConnectionOptions { */ retryOverallTimeoutSecs?: number /** - * Enable kernel telemetry export. Omitted / `false` keeps telemetry - * disabled. When enabled, the kernel records operation telemetry below the - * binding layer and exports through the Databricks SQL driver telemetry - * endpoint. + * Enable kernel telemetry export. Tri-state: an explicit `true` or `false` + * takes precedence; when omitted, export defers to the + * `enableTelemetryForKernel` workspace feature flag, falling back to + * disabled when the flag is absent. Only an explicit `false` guarantees + * telemetry stays disabled. When enabled, the kernel records operation + * telemetry below the binding layer and exports through the Databricks SQL + * driver telemetry endpoint. */ telemetryEnabled?: boolean /** @@ -576,9 +1021,9 @@ export interface ConnectionOptions { /** Enable telemetry circuit-breaker protection. Omitted ⇒ kernel default. */ telemetryCircuitBreakerEnabled?: boolean /** - * Consecutive telemetry export failures before opening the circuit. Omitted - * ⇒ kernel default. Must be greater than zero when the circuit breaker is - * enabled. + * Consecutive telemetry export failures before opening the circuit. + * Omitted ⇒ kernel default. Must be greater than zero when the circuit + * breaker is enabled. */ telemetryCircuitBreakerThreshold?: number /** @@ -615,47 +1060,140 @@ export interface ConnectionOptions { */ socketTimeoutMs?: number } + /** - * Open a Databricks SQL session and return an opaque `Connection` - * wrapping the kernel `Session`. Authentication is selected by - * `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see - * [`build_auth_config`]. - * - * The JS-visible name is `openSession` (napi-rs converts snake_case - * to camelCase for free functions). - */ -export declare function openSession(options: ConnectionOptions): Promise -/** - * One kernel log event, as handed to JS. `level` is a lower-case string - * (`error`/`warn`/`info`/`debug`/`trace`) the Node side maps onto its - * `LogLevel`; `target` is the originating `tracing` target (e.g. - * `databricks::sql::kernel`); `message` is the rendered event plus any - * structured `key=value` fields. - */ -export interface LogRecord { - level: string - target: string - message: string -} -/** - * Install (idempotently) the kernel→JS log bridge and set its level. + * Per-statement options for `Connection.executeStatement`. * - * `callback` is invoked with **an array of [`LogRecord`]s** (`(err, records)`) - * for each forwarded batch. `level` is one of - * `off`/`error`/`warn`/`info`/`debug`/`trace` (case-insensitive); unknown - * values fall back to `warn`. + * Mirrors the kernel `StatementSpec` knobs that are safe to thread + * through napi without a kernel-side change. Today this covers: + * - `statementConf` — per-statement Spark conf overlay + * (`StatementSpec.statement_conf` → SEA `parameters` / + * Thrift `confOverlay`) + * - `queryTags` — convenience wrapper over `statementConf` with + * key `query_tags`; serialised to the same comma-separated + * `key:value` wire shape NodeJS Thrift's `serializeQueryTags` + * produces (`lib/utils/queryTags.ts`). Backslashes in keys are + * doubled; backslash/colon/comma in values are backslash-escaped. * - * Safe to call more than once: the process-global subscriber is installed on - * the first call only, while every call refreshes the sink + level (last - * writer wins — see module docs). - */ -export declare function initKernelLogging(callback: (err: Error | null, arg: Array) => any, level: string): void -/** - * Snapshot of the bridge's runtime state for observability. + * `rowLimit` (SEA `row_limit`) is exposed here and threaded onto the kernel + * `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`) + * carry bound query parameters, decoded via `params::parse_typed_value`. + * `rawParams` forwards pre-marshalled SEA parameters unchanged. + * (There is no `queryTimeoutSecs`: it abused the SEA `wait_timeout` inline-hold + * window and was removed — a real per-statement timeout is `STATEMENT_TIMEOUT`.) * - * `installed` is `true` only when the process-global subscriber was - * successfully installed by *this* bridge (and the drain thread started); - * `false` means another global subscriber was already set or the drain + * **Tag-order caveat (M4 parity note).** The napi `queryTags` field + * is a Rust `HashMap` whose iteration order is + * non-deterministic, so the serialised `query_tags` value may have + * a different key order than Thrift's `serializeQueryTags` (which + * iterates `Object.keys(...)` in insertion order) for the same + * input. The SEA server is order-insensitive on conf values, so + * the two are functionally equivalent. If a caller needs + * byte-identical Thrift parity, the JS adapter pre-serialises via + * `serializeQueryTags` and writes the result into + * `statementConf["query_tags"]` directly — see + * `KernelSessionBackend.executeStatement` in the NodeJS driver. This + * path is the one the production code uses. + */ +export interface ExecuteOptions { + /** + * Per-statement Spark conf overlay. Merged on top of the + * session-level `sessionConf` at execute time; this map wins + * on key collisions. Unknown keys are rejected by the server. + */ + statementConf?: Record + /** + * Query tags as key→value pairs. Serialised to a comma- + * separated `key:value` string (backslash-escaping `\`, `:`, + * `,`) and placed into `statementConf["query_tags"]`, matching + * NodeJS Thrift's `serializeQueryTags` wire shape. Passing + * both `queryTags` AND a `query_tags` key in `statementConf` + * raises `InvalidArgument` — the caller's intent is ambiguous + * so we refuse to silently pick one over the other. + * + * A **`null`** value emits a **bare key** (no colon) — e.g. + * `{ production: null }` → `"production"` — matching the + * connectors' `key`-only tag form. + * + * See the struct-level "Tag-order caveat" for the + * HashMap-iteration-order vs `Object.keys`-iteration-order + * divergence and the byte-identical-Thrift-parity workaround. + */ + queryTags?: Record + /** + * Server-side cap on the number of rows this statement returns + * (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to + * `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. + */ + rowLimit?: number + /** + * Positional parameters, in 1-based wire order. Index `i` in this + * Vec corresponds to the `i+1`-th `?` placeholder in the SQL. + * Each entry is a `{ sqlType, value }` pair — `value` is the + * string-encoded literal or `null` for SQL NULL. Mirrors + * `StatementSpec::positional_params`; decoded via [`parse_typed_value`]. + */ + positionalParams?: Array + /** + * Named parameters (`:name` placeholders). Each carries its `name` + * alongside the `{ sqlType, value? }` pair. Mapped to a kernel + * `TypedValue` via the same [`parse_typed_value`] codec and bound with + * `StatementSpec::param_named`. Named is the SEA-spec-required public + * param form (`StatementParameter.name` is `openapi_required`); + * positional is the documented-undocumented variant. The two are + * mutually exclusive at the SQL level (`?` vs `:name`). + */ + namedParams?: Array + /** + * Pre-marshalled parameters passed through `StatementSpec::param_raw`. + * Omit `name` for positional values. Raw parameters cannot be mixed with + * typed parameters or combine named and positional markers. + */ + rawParams?: Array +} + +/** + * A single extra HTTP header as an explicit `{ name, value }` pair. + * + * An ordered list of these (`ConnectionOptions.custom_headers`) mirrors + * the kernel core's `Vec<(String, String)>` and the pyo3 binding's + * `http_headers`: order is preserved and duplicate `name`s are allowed. + * A struct (rather than a raw `[name, value]` tuple) because napi-rs + * does not marshal Rust tuples through `#[napi(object)]` fields; the + * struct is the idiomatic, self-documenting equivalent and maps to a JS + * `{ name: string, value: string }`. + */ +export interface HeaderEntry { + name: string + value: string +} + +/** + * Install (idempotently) the kernel→JS log bridge and set its level. + * + * `callback` is invoked with **an array of [`LogRecord`]s** (`(err, records)`) + * for each forwarded batch. `level` is one of + * `off`/`error`/`warn`/`info`/`debug`/`trace` (case-insensitive); unknown + * values fall back to `warn`. + * + * Safe to call more than once: the process-global subscriber is installed on + * the first call only, while every call refreshes the sink + level (last + * writer wins — see module docs). + */ +export declare function initKernelLogging(callback: ((err: Error | null, arg: Array) => any), level: string): void + +/** + * Return the bridge's [`KernelLoggingStats`]. Safe to call before + * `initKernelLogging` (reports `installed: false`, `dropped: 0`). + */ +export declare function kernelLoggingStats(): KernelLoggingStats + +/** + * Snapshot of the bridge's runtime state for observability. + * + * `installed` is `true` only when the process-global subscriber was + * successfully installed by *this* bridge (and the drain thread started); + * `false` means another global subscriber was already set or the drain * thread could not be spawned, so kernel logs are NOT reaching the JS sink. * `dropped` is the cumulative count of records discarded because the * bounded channel was full during a burst (drop-newest) — a nonzero, @@ -665,16 +1203,81 @@ export interface KernelLoggingStats { installed: boolean dropped: number } + /** - * Return the bridge's [`KernelLoggingStats`]. Safe to call before - * `initKernelLogging` (reports `installed: false`, `dropped: 0`). + * One kernel log event, as handed to JS. `level` is a lower-case string + * (`error`/`warn`/`info`/`debug`/`trace`) the Node side maps onto its + * `LogLevel`; `target` is the originating `tracing` target (e.g. + * `databricks::sql::kernel`); `message` is the rendered event plus any + * structured `key=value` fields. */ -export declare function kernelLoggingStats(): KernelLoggingStats +export interface LogRecord { + level: string + target: string + message: string +} + +/** + * A named bound parameter — a [`TypedValueInput`] plus its `:name`. Kept a + * distinct napi object (rather than an optional `name` on `TypedValueInput`) + * so the positional surface stays a clean ordered list with no name field. + */ +export interface NamedTypedValueInput { + name: string + sqlType: string + value?: string +} + +/** + * Open a Databricks SQL session and return an opaque `Connection` + * wrapping the kernel `Session`. Authentication is selected by + * `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see + * [`build_auth_config`]. + * + * The JS-visible name is `openSession` (napi-rs converts snake_case + * to camelCase for free functions). + */ +export declare function openSession(options: ConnectionOptions): Promise + +/** + * Programmatic HTTP/HTTPS proxy configuration, mirroring the kernel's + * internal [`ProxyConfig`]. Supplied as a structured object rather than a + * flattened URL so credentials never have to be percent-encoded into the URL + * and the bypass-host list can be expressed. + * + * - `url` — proxy endpoint, e.g. `"http://proxy.corp.example.com:8080"`. Must + * use the `http://` or `https://` scheme. + * - `username` / `password` — optional proxy basic-auth, applied via + * `reqwest`'s `Proxy::basic_auth` (not embedded in the URL). + * - `bypassHosts` — optional comma-separated host/domain list that should + * bypass the proxy (e.g. `"localhost,*.internal.corp"`). + */ +export interface ProxyInput { + url: string + username?: string + password?: string + bypassHosts?: string +} + +/** + * A pre-marshalled SEA parameter that preserves `sql_type` verbatim. + * Omit `name` for positional markers; the kernel assigns their ordinals. + */ +export interface RawParameterInput { + /** Named marker name. Omit for a positional marker. */ + name?: string + /** Databricks SQL type name sent verbatim to SEA. */ + sqlType: string + /** String-encoded value. `None` represents SQL NULL. */ + value?: string +} + /** * Live-retarget the bridge's level (one of * `off`/`error`/`warn`/`info`/`debug`/`trace`, case-insensitive). */ export declare function setKernelLogLevel(level: string): void + /** * JS-visible binding for a single positional parameter. * @@ -708,41 +1311,7 @@ export interface TypedValueInput { */ value?: string } -/** - * A pre-marshalled SEA parameter that preserves `sql_type` verbatim. - * Omit `name` for positional markers; the kernel assigns their ordinals. - */ -export interface RawParameterInput { - /** Named marker name. Omit for a positional marker. */ - name?: string - /** Databricks SQL type name sent verbatim to SEA. */ - sqlType: string - /** String-encoded value. `None` represents SQL NULL. */ - value?: string -} -/** - * A single Arrow IPC stream payload encoding one record batch (plus - * the schema header so the JS-side reader is stateless). - */ -export interface ArrowBatch { - /** - * Arrow IPC stream payload (schema header + 1 record-batch - * message). Decode with `apache-arrow`'s `RecordBatchReader`. - */ - ipcBytes: Buffer -} -/** - * An Arrow IPC stream payload encoding just the result schema (no - * record-batch messages). Returned by `Statement.schema()`. - */ -export interface ArrowSchema { - /** - * Arrow IPC stream payload (schema header only, no record-batch - * messages). Decode with `apache-arrow`'s `RecordBatchReader` — - * the reader will expose the schema and immediately end. - */ - ipcBytes: Buffer -} + /** * Returns the native binding's crate version (`CARGO_PKG_VERSION`). * @@ -750,541 +1319,3 @@ export interface ArrowSchema { * loaded?" probe for the JS-side loader's structured diagnostics. */ export declare function version(): string -/** - * Opaque async-statement handle. - * - * Returned by `Connection.submitStatement(...)` after the kernel - * `Statement::submit()` returns (server sent `wait_timeout=0s`, so - * the response carries a `statement_id` but the statement is still - * `Pending`/`Running`). JS drives polling via `status()` / - * `awaitResult()`. - * - * Concurrency shape: `status()`, `awaitResult()`, and `close()` take - * `inner.lock()` and hold the guard across the kernel `.await` (tokio - * `Mutex` is FIFO), so `status()` / `close()` queue behind any - * in-flight `awaitResult()` until it returns naturally. `cancel()` is - * the deliberate exception: it does **not** touch `inner` — it fires - * through the detached `AsyncStatementCanceller` (session + - * statement_id, captured at construction), so an explicit - * `stmt.cancel()` interrupts an in-flight `awaitResult()` instead of - * queueing behind it. The server-side cancel flips the statement - * terminal, which the parked `awaitResult()` poll loop observes - * (`Cancelled`) and returns on. The kernel's `AwaitResultCancelGuard` - * still covers the drop-cancel case (Promise.race / timeout) - * independently — see module docs. - */ -export declare class AsyncStatement { - /** - * Server-issued statement id. Cached at construction; readable - * even after `close()` so JS-side log lines can correlate - * against kernel / server logs which key on the same id. - */ - get statementId(): string - /** - * One-shot status check. Returns a string enum matching the - * kernel `StatementStatus` shape: - * `'Pending' | 'Running' | 'Succeeded' | 'Failed' | - * 'Cancelled' | 'Closed' | 'Unknown'`. (`'Unknown'` is the - * `#[non_exhaustive]` forward-compat catch-all that - * `StatementStatus::as_str` can return — consumers switching on - * the state must handle it.) Returns - * `KernelError(InvalidStatementHandle)` if the statement has - * been explicitly `close()`d. - * - * The `Failed` variant collapses to the string `'Failed'` on - * the JS side; the underlying error envelope (sql_state / - * error_code / query_id) is surfaced by `awaitResult()`'s - * rejection, which is where callers actually need the typed - * error. `status()` is intended for polling progress UIs - * that only need the state name. - */ - status(): Promise - /** Rows modified by the statement (UPDATE / INSERT / DELETE / MERGE). */ - numModifiedRows(): Promise - /** - * Server-supplied user-facing message (may contain SQL fragments — - * redact before centralised logging). - */ - displayMessage(): Promise - /** Server-supplied diagnostic detail. */ - diagnosticInfo(): Promise - /** Server-supplied structured error detail (JSON), when enabled. */ - errorDetailsJson(): Promise - /** - * Block until the server reaches a terminal state, then return - * an `AsyncResultHandle` that wraps the materialised result - * stream. The handle exposes `fetchNextBatch()` / `schema()` - * for consuming the result, plus `statementId` for log - * correlation. - * - * Drop-cancel safety: kernel `await_result` installs - * `AwaitResultCancelGuard` which fires a fire-and-forget - * `cancel_statement` if the future is dropped mid-poll - * (timeout, tokio::select! loser, JS-side `Promise.race` - * loser). The `util::guarded` `catch_unwind` here covers the - * V8-panic-across-boundary case on top. Returns - * `KernelError(InvalidStatementHandle)` if the statement has - * been explicitly `close()`d. - */ - awaitResult(): Promise - /** - * Server-side cancel. Returns - * `KernelError(InvalidStatementHandle)` if the statement has - * been explicitly `close()`d. Idempotent against a server - * that already reached a terminal state — the kernel's - * `cancel_statement` is a no-op there. - * - * **Lock-free by design.** Unlike `status()` / `awaitResult()` / - * `close()`, this does not take `inner.lock()` — it fires through - * the detached `AsyncStatementCanceller` captured at construction. - * That lets `stmt.cancel()` interrupt an in-flight `awaitResult()` - * (which holds the mutex for the whole poll) instead of queueing - * behind it: the server-side cancel flips the statement terminal, - * the parked `awaitResult()` poll loop observes `Cancelled` and - * returns. The closed-state check reads a lock-free flag so a - * cancel after an explicit `close()` still surfaces - * `InvalidStatementHandle`. - */ - cancel(): Promise - /** - * Explicit close. Idempotent — a second call on an - * already-closed handle returns `Ok(())`. On `Err`, the napi - * inner is already `None`, so a JS-side retry sees the - * closed-handle short-circuit and returns `Ok(())` without - * re-attempting the wire call. The kernel's own `Drop` - * fire-and-forget retry runs once in the background. - */ - close(): Promise -} -/** - * Opaque result-fetch handle returned by - * `AsyncStatement.awaitResult()`. Wraps a kernel `ResultStream` - * directly; structurally analogous to the sync `Statement`'s - * fetch-side surface (`fetchNextBatch` / `schema` / - * `statementId`). - * - * `cancel()` / `close()` are not exposed: the parent - * `AsyncStatement` owns server-side lifecycle. A `close()` here - * would create dual-ownership of the same statement_id with - * inconsistent close semantics. Callers `close()` the parent - * `AsyncStatement` after they're done fetching. - * - * Schema is cached at construction so it survives the underlying - * stream being drained; mirrors the sync `Statement.schema()` - * post-close contract. - */ -export declare class AsyncResultHandle { - /** - * Server-issued statement id. Cached at construction; readable - * for log correlation. Matches the parent `AsyncStatement`'s - * `statementId`. - */ - get statementId(): string - /** - * Pull the next batch of results. Returns `null` when the - * stream is exhausted. The returned `ArrowBatch.ipcBytes` is a - * complete Arrow IPC stream (schema header + 1 record-batch - * message), suitable for handing to `apache-arrow`'s - * `RecordBatchReader`. Byte-identical to the sync - * `Statement.fetchNextBatch()` payload for the same query. - */ - fetchNextBatch(): Promise - /** - * Result schema as an Arrow IPC payload (schema header only, - * no record-batch message). Available before any batches have - * been fetched. Sync because the body has no `.await` — - * `encode_ipc_stream` is pure CPU work over the cached - * `Arc`. - */ - schema(): ArrowSchema -} -/** - * Handle returned by `Connection.executeStatementCancellable`. Owns the - * built-but-not-yet-executed kernel `Statement` plus a detached - * [`StatementCanceller`] captured before dispatch, so JS can fire a - * server-side cancel while the blocking `result()` is in flight. - * - * `pending` is `Arc>>` so `result()` can - * `.take()` the statement (the kernel `execute()` borrows it `&mut`, - * then it moves into the produced `Statement` wrapper to keep its - * `ValidityFlag` set — see `statement.rs`). A second `result()` call - * after the first resolved surfaces `InvalidStatementHandle`. - */ -export declare class CancellableExecution { - /** - * The server-issued statement id this execution targets, if the - * server has issued one yet (`null` before the initial submit - * round-trip publishes it mid-`result()`). Useful for log - * correlation while the blocking drive is in flight. - */ - get statementId(): string | null - /** - * Drive the blocking `execute()` and resolve to a `Statement` - * (identical to what `executeStatement` returns) once the kernel - * reaches a terminal state and the result stream is ready. - * - * Consumes the pending statement: a second `result()` call returns - * `KernelError(InvalidStatementHandle)`. The future is - * drop-cancel-safe — the kernel's per-execute `MidExecuteCancelState` - * guard fires a fire-and-forget `cancel_statement` if this future is - * dropped mid-flight (`Promise.race` / timeout loser), independently - * of an explicit `cancel()`. - * - * On a server-side cancel the kernel's blocking `execute()` currently - * surfaces `InvalidArgument` (a known kernel quirk — the async path - * returns `Cancelled`). When this handle's `cancel()` actually dispatched a - * server-side cancel, we normalise that into `Cancelled` here so JS callers - * can rely on a single cancelled-status code regardless of execution path. - * - * Three outcomes can race the blocking drive: (1) a natural terminal state - * → `Ok` or the genuine error; (2) an explicit `cancel()` that dispatched a - * server cancel → this `result()` rejects with a `Cancelled`-coded error - * (the normalisation above); (3) the future being **dropped** mid-flight - * (`Promise.race`/timeout loser) → the kernel's `MidExecuteCancelState` - * drop-guard fires a fire-and-forget `cancel_statement`, but there is no - * `result()` left to observe a code. Only (2) yields a `Cancelled` error. - */ - result(): Promise - /** - * Server-side cancel of the in-flight statement. - * - * Lock-free: fires the detached `StatementCanceller` captured at - * construction rather than taking the mutex `result()` holds, so it - * interrupts a still-running blocking `result()` instead of queueing - * behind it. No-op (returns `Ok`) if `result()` already finished - * successfully, or if no statement id has been observed yet (query still - * in its initial submit round-trip), and idempotent against a server - * already in a terminal state. - */ - cancel(): Promise -} -/** - * Opaque connection handle wrapping a kernel `Session`. - * - * `inner` is `Arc>>` so: - * - the Drop impl can clone the `Arc` and `.take()` the session on a - * background tokio task without holding `&mut self` (which Drop is - * forbidden from doing across an `await`), - * - `close()` can `.take()` the session to consume it for the kernel's - * move-by-value `Session::close(self)` signature. - * - * **Concurrency shape** — both `executeStatement` and - * `submitStatement` build the kernel `Statement` under `inner.lock()` - * and then RELEASE the guard before the wire call - * (`stmt.execute().await` / `stmt.submit().await`). `Session::statement()` - * is `&self`-callable and only clones the session's internal `Arc`, so - * the built statement is independent of the guard. Concurrent - * `Promise.all([executeStatement(q1), submitStatement(q2)])` therefore - * serialise only for the microsecond statement-build, not the network - * round-trip, and `close()` never blocks behind an in-flight execute or - * submit. See - * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. - */ -export declare class Connection { - /** - * Server-issued session id. Cached at construction; readable - * even after `close()` so JS-side log lines can correlate - * against kernel / server logs which key on the same id. - */ - get sessionId(): string - /** - * Execute a SQL statement and return a Statement handle that - * streams batches via `fetchNextBatch()`. - * - * Catalog / schema / sessionConf are session-level - * (`openSession`). Per-statement options on `ExecuteOptions`: - * - `statementConf` — per-statement Spark conf overlay - * - `queryTags` — serialised to a comma-separated `key:value` - * string and placed in `statement_conf["query_tags"]`, - * matching NodeJS Thrift's `serializeQueryTags` wire shape - * - * `options` is omitted/`None` for the no-options path; passing - * `{ statementConf: {} }` (an empty map) is treated the same as - * omission to keep the wire shape stable for the common case. - */ - executeStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise - /** - * directResults execute — the Thrift/JDBC model. Sends ExecuteStatement - * with no `wait_timeout` field (server applies its ~10s default inline wait - * and auto-closes on success) and returns WITHOUT polling past it: - * - * - a **`Statement`** (left arm) when the query finished within the inline - * wait — terminal, result ready inline, `close()` is a clean release; - * - an **`AsyncStatement`** (right arm) when it did not — a poll/cancel - * handle the caller drives (`status()` / `awaitResult()` / `cancel()`). - * - * JS distinguishes the arms by feature-detecting `awaitResult` (present - * only on `AsyncStatement`). This is the path that gives mid-run cancel for - * long queries WITHOUT the eager-handle / close-drives workaround: the - * returned handle always corresponds to a server-owned statement. - * - * **Load-bearing contract:** the kernel's `DirectStatement::{Completed, - * Running}` discriminant cannot ride on these opaque `#[napi]` classes, so - * consumers MUST feature-detect via `awaitResult` (the only member unique to - * `AsyncStatement`). `Statement` (the Completed arm) MUST NOT gain an - * `awaitResult` member, or every consumer silently misroutes. The pyo3 - * binding makes the same `await_result`-probe assumption. - */ - executeStatementDirect(sql: string, options?: ExecuteOptions | undefined | null): Promise - /** - * Execute a SQL statement on the blocking (sync) path, but return a - * `CancellableExecution` handle so a concurrent JS task can cancel - * the query *while it is still running server-side*. - * - * `executeStatement` builds the kernel `Statement`, awaits the - * blocking `execute()`, and only then hands JS a `Statement` — so a - * query that runs for several seconds is uncancellable from JS on - * that path (there is no handle until the blocking call resolves). - * This method instead builds the statement, captures a detached - * `StatementCanceller` **before** dispatching `execute()`, and hands - * JS a `CancellableExecution` immediately. The caller drives the - * blocking execution via `result()` (resolves to the same - * `Statement` `executeStatement` returns) and can fire `cancel()` - * concurrently to interrupt a still-running query mid-COMPUTE. - * - * Option semantics are identical to `executeStatement`. - * Mirrors the pyo3 `Statement.canceller()` / `Statement.execute()` - * split (PR #121): obtain the canceller before the blocking drive. - */ - executeStatementCancellable(sql: string, options?: ExecuteOptions | undefined | null): Promise - /** - * Submit a SQL statement and return immediately with an - * `AsyncStatement` handle, without blocking until the query - * finishes. The kernel's `Statement::submit()` sends - * `wait_timeout=0s`, so the server responds as soon as it has a - * `statement_id` (state `Pending`/`Running`); JS drives polling - * via `AsyncStatement.status()` and materialises results with - * `AsyncStatement.awaitResult()`. - * - * This is the async-execution path the Thrift backend always - * uses (`runAsync: true`): the SEA backend submits, returns a - * pending operation handle, and polls to terminal during - * fetch. Option semantics (statementConf / queryTags / - * rowLimit / positional + named params) match `executeStatement`. - * Submit always sends `wait_timeout=0s` so the call returns - * immediately; the caller drives completion via `status()` / - * `awaitResult()`. Only the blocking-vs-pending return contract - * differs from `executeStatement`. - */ - submitStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise - /** - * Explicit close. Awaits the server-side `DeleteSession` so the - * JS caller can observe failures (auth revoked mid-session, - * warehouse stopped, network error). Idempotent — a second call - * on an already-closed connection returns `Ok`. - * - * **Errors are terminal from the JS side.** The kernel session - * handle is consumed (`take()`) BEFORE the wire `DeleteSession` - * runs, because `Session::close` takes `self` by value. On `Err`, - * the napi `inner` is already `None`, so a JS-side retry sees a - * closed connection and returns `Ok(())` without re-attempting - * the wire call. The kernel's own `Drop` fire-and-forget retry - * runs once in the background — the JS caller can log the error - * but cannot drive a retry. If you need retry-on-failure - * semantics for `DeleteSession`, layer them above this method. - */ - close(): Promise - /** - * All catalogs visible to the session. - * - * JDBC `getCatalogs` shape: `TABLE_CAT: Utf8`. - */ - listCatalogs(): Promise - /** - * Schemas filtered by catalog (exact) and schema name pattern. - * - * JDBC `getSchemas` shape: `TABLE_SCHEM, TABLE_CATALOG`. - */ - listSchemas(catalog?: string | undefined | null, schemaPattern?: string | undefined | null): Promise - /** - * Tables filtered by catalog (exact), schema (pattern), table (pattern). - * - * JDBC `getTables` shape: 10 columns. `tableTypes`, when provided, - * filters rows by `TABLE_TYPE` kernel-side. - * - * `tableTypes` is an advisory filter. Databricks `SHOW TABLES` does - * NOT honour the table-type filter server-side; the kernel applies - * it client-side after the result returns. Callers expecting - * server-side rejection of off-type tables should not rely on this. - */ - listTables(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, tableTypes?: Array | undefined | null): Promise - /** - * Columns of tables matching the filter. - * - * JDBC `getColumns` shape: 23 columns. - */ - listColumns(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, columnPattern?: string | undefined | null): Promise - /** - * Functions visible to the session. `catalog` is exact; - * `schemaPattern` and `functionPattern` are SQL LIKE. - */ - listFunctions(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, functionPattern?: string | undefined | null): Promise - /** - * Procedures visible to the session. `catalog` is exact; - * `schemaPattern` and `procedurePattern` are SQL LIKE. - */ - listProcedures(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, procedurePattern?: string | undefined | null): Promise - /** - * All table types (`TABLE`, `VIEW`, `SYSTEM TABLE`, …). - * No wire call — static in-memory result. - */ - listTableTypes(): Promise - /** - * SQL data types supported by the workspace. - * No wire call — static in-memory result. - */ - listTypeInfo(): Promise - /** - * Primary keys for the given table. All three identifiers are - * exact — ODBC `SQLPrimaryKeys` does not support patterns. - */ - getPrimaryKeys(catalog: string | undefined | null, schema: string | undefined | null, table: string): Promise - /** - * Foreign-key relationships. The parent side is optional. When the - * foreign table is omitted, returns an empty result without issuing a - * server statement. When it is provided, its catalog and schema are - * required. All identifiers are exact — no LIKE patterns. - */ - getCrossReference(parentCatalog: string | undefined | null, parentSchema: string | undefined | null, parentTable: string | undefined | null, foreignCatalog: string | undefined | null, foreignSchema: string | undefined | null, foreignTable: string | undefined | null): Promise -} -/** - * Opaque executed-statement handle. - * - * **Current concurrency shape** — every method takes `inner.lock()` - * and holds the guard across the kernel `.await`. tokio `Mutex` is - * FIFO, so cancel/close queue behind any in-flight `fetchNextBatch` - * until it returns naturally. This is a known limitation that exists - * because the napi shape has not yet been split into an - * `Arc` (for cancel/close, which the - * kernel exposes as `&self`-callable) plus a `Mutex>` only - * for the borrowed-mut fetch path. The lock-shape refactor needs a - * small kernel-side accessor and lands in a follow-up PR — see - * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. - * - * `schema` and `statement_id` are cached at construction so they - * survive `close()` — JS callers building error reports against a - * disposed statement can still read them. - */ -export declare class Statement { - /** - * Server-issued statement id. Cached at construction; readable - * even after `close()` so JS-side log lines can correlate against - * kernel / server logs which key on the same id. - */ - get statementId(): string - /** - * Number of rows modified by the statement (UPDATE / INSERT / - * DELETE / MERGE). `null` for SELECT and on warehouses that don't - * surface the counter. Mirrors Thrift's - * `TGetOperationStatusResp.numModifiedRows`. - */ - numModifiedRows(): Promise - /** - * Server-supplied user-facing message. Mirrors Thrift's - * `TGetOperationStatusResp.displayMessage`. **PII / sensitive- - * data note:** may contain SQL fragments or parameter values — - * redact before centralised logging. - * - * Populated on `Succeeded` / `Closed` paths (incl. an empty `Closed`). - * On terminal-error states (`Failed` / `Cancelled`) the kernel returns - * an Error instead of a `Statement`, and the same field rides on the JS - * Error envelope under the same `displayMessage` key. - */ - displayMessage(): Promise - /** - * Server-supplied diagnostic detail — multi-line operator / - * stack context. Mirrors Thrift's - * `TGetOperationStatusResp.diagnosticInfo`. For support surfaces, - * not user-facing. Same reachability + PII caveats as - * `displayMessage`. - */ - diagnosticInfo(): Promise - /** - * Server-supplied JSON blob with extended error details. Mirrors - * Thrift's `TGetOperationStatusResp.errorDetailsJson`. - * Pass-through string — JS callers parse with `JSON.parse` if - * they need structured access. - * - * **Server-side gating:** populated only when the workspace has - * `spark.databricks.sql.errorDetailsJson.enabled = true` on the - * underlying SQL cluster. The flag is internal-only / default- - * false in the Databricks runtime, so for most JS callers this - * will return `null`. Admin-enabled workspaces return content - * shaped like `{"errorClass": "...", "messageTemplate": "..."}`. - * - * **Unbounded:** when populated, server can return a multi-MB - * blob; size before logging. - */ - errorDetailsJson(): Promise - /** - * Pull the next batch of results. Returns `null` when the stream - * is exhausted. The returned `ArrowBatch.ipcBytes` is a complete - * Arrow IPC stream (schema header + 1 record-batch message) - * suitable for handing to `apache-arrow`'s `RecordBatchReader`. - * - * On `Err`, the stream is in an unspecified state — call - * `close()` and discard the `Statement`. Subsequent - * `fetchNextBatch()` calls after an error are not guaranteed to - * succeed or fail consistently. - */ - fetchNextBatch(): Promise - /** - * Result schema as an Arrow IPC payload (schema header only, no - * record-batch message). Available before any batches have been - * fetched, and remains available after `close()` — the kernel - * materialises the schema eagerly so JS callers can build error - * reports against a disposed statement. - * - * Sync because the body has no `.await` — `encode_ipc_stream` is - * pure CPU work over an `Arc` already cached on the - * wrapper. Mirrors `pyo3/src/statement.rs::arrow_schema` (sync). - * napi-rs converts a panic in a sync `#[napi]` entry point into a - * thrown JS error via its own macro-expanded boundary, so the - * `util::guarded` `catch_unwind` wrapper that the `async fn` - * entry points use is not required for this method. - */ - schema(): ArrowSchema - /** - * Server-side cancel. - * - * For executed statements: short-circuits to `Ok(())` if - * `fetchNextBatch` has already returned `null` (stream - * naturally exhausted) — matches the JDBC `Statement.cancel()` - * no-op-after-completion contract, so JS callers can fire cancel - * defensively without distinguishing "real cancel" from "raced - * with natural completion." - * - * For metadata streams: no-op (the kernel has no in-flight - * cancellation surface for metadata calls today). - * - * Returns `KernelError(InvalidStatementHandle)` if the statement - * has been explicitly `close()`d. - */ - cancel(): Promise - /** - * Explicit close. - * - * For executed statements: awaits the server-side `CloseStatement` - * so the JS caller can observe failures (auth revoked mid-session, - * network error, server-side error). Idempotent — a second call - * on an already-closed statement returns `Ok`. - * - * **Errors are terminal from the JS side.** The kernel executed - * handle is taken out of `inner` BEFORE the wire `CloseStatement` - * runs (so `Drop` knows there's nothing left to clean up). On - * `Err`, the napi `inner` is already `None`, so a JS-side retry - * sees a closed statement and returns `Ok(())` without re- - * attempting the wire call. The kernel-level `ExecutedStatement` - * has been consumed at that point and the value is dropped on - * the way out of the closure — the kernel's `ExecutedStatement:: - * Drop` then fires-and-forgets a single retry on the captured - * runtime. The JS caller can log the error but cannot drive a - * further retry. If you need retry-on-failure semantics for - * `CloseStatement`, layer them above this method. - * - * For metadata streams: drops the stream (no server round-trip - * needed — metadata results have no in-flight server-side - * resource to release). - */ - close(): Promise -} diff --git a/napi/index.js b/napi/index.js index ad50ecc9..6902ddee 100644 --- a/napi/index.js +++ b/napi/index.js @@ -1,325 +1,713 @@ -/* tslint:disable */ +// prettier-ignore /* eslint-disable */ -/* prettier-ignore */ - +// @ts-nocheck /* auto-generated by NAPI-RS */ -const { existsSync, readFileSync } = require('fs') -const { join } = require('path') +const { readFileSync } = require('fs') +let nativeBinding = null +const loadErrors = [] -const { platform, arch } = process +const isMusl = () => { + let musl = false + if (process.platform === 'linux') { + musl = isMuslFromFilesystem() + if (musl === null) { + musl = isMuslFromReport() + } + if (musl === null) { + musl = isMuslFromChildProcess() + } + } + return musl +} -let nativeBinding = null -let localFileExisted = false -let loadError = null +const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-') -function isMusl() { - // For Node 10 - if (!process.report || typeof process.report.getReport !== 'function') { - try { - const lddPath = require('child_process').execSync('which ldd').toString().trim() - return readFileSync(lddPath, 'utf8').includes('musl') - } catch (e) { +const isMuslFromFilesystem = () => { + try { + return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl') + } catch { + return null + } +} + +const isMuslFromReport = () => { + let report = null + if (process.report && typeof process.report.getReport === 'function') { + process.report.excludeNetwork = true + report = process.report.getReport() + } + if (!report) { + return null + } + if (report.header && report.header.glibcVersionRuntime) { + return false + } + if (Array.isArray(report.sharedObjects)) { + if (report.sharedObjects.some(isFileMusl)) { return true } - } else { - const { glibcVersionRuntime } = process.report.getReport().header - return !glibcVersionRuntime } + return false } -switch (platform) { - case 'android': - switch (arch) { - case 'arm64': - localFileExisted = existsSync(join(__dirname, 'index.android-arm64.node')) +const isMuslFromChildProcess = () => { + try { + return require('child_process').execSync('ldd --version', { encoding: 'utf8' }).includes('musl') + } catch (e) { + // If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false + return false + } +} + +function requireNative() { + if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) { + try { + return require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH); + } catch (err) { + loadErrors.push(err) + } + } else if (process.platform === 'android') { + if (process.arch === 'arm64') { + try { + return require('./index.android-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-android-arm64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-android-arm64/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm') { + try { + return require('./index.android-arm-eabi.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-android-arm-eabi') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-android-arm-eabi/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`)) + } + } else if (process.platform === 'win32') { + if (process.arch === 'x64') { + if ((process.config && process.config.variables && process.config.variables.shlib_suffix === 'dll.a') || (process.config && process.config.variables && process.config.variables.node_target_type === 'shared_library')) { try { - if (localFileExisted) { - nativeBinding = require('./index.android-arm64.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-android-arm64') - } + return require('./index.win32-x64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-win32-x64-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-x64-gnu/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./index.win32-x64-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-win32-x64-msvc') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-x64-msvc/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'ia32') { + try { + return require('./index.win32-ia32-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-win32-ia32-msvc') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-ia32-msvc/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./index.win32-arm64-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-win32-arm64-msvc') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-arm64-msvc/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`)) + } + } else if (process.platform === 'darwin') { + try { + return require('./index.darwin-universal.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-darwin-universal') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-darwin-universal/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + if (process.arch === 'x64') { + try { + return require('./index.darwin-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-darwin-x64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-darwin-x64/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./index.darwin-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-darwin-arm64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-darwin-arm64/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`)) + } + } else if (process.platform === 'freebsd') { + if (process.arch === 'x64') { + try { + return require('./index.freebsd-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-freebsd-x64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-freebsd-x64/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./index.freebsd-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-freebsd-arm64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-freebsd-arm64/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`)) + } + } else if (process.platform === 'linux') { + if (process.arch === 'x64') { + if (isMusl()) { + try { + return require('./index.linux-x64-musl.node') } catch (e) { - loadError = e + loadErrors.push(e) } - break - case 'arm': - localFileExisted = existsSync(join(__dirname, 'index.android-arm-eabi.node')) try { - if (localFileExisted) { - nativeBinding = require('./index.android-arm-eabi.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-android-arm-eabi') + const binding = require('@databricks/databricks-sql-kernel-linux-x64-musl') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-x64-musl/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding } catch (e) { - loadError = e + loadErrors.push(e) } - break - default: - throw new Error(`Unsupported architecture on Android ${arch}`) - } - break - case 'win32': - switch (arch) { - case 'x64': - localFileExisted = existsSync( - join(__dirname, 'index.win32-x64-msvc.node') - ) + } else { try { - if (localFileExisted) { - nativeBinding = require('./index.win32-x64-msvc.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-win32-x64-msvc') - } + return require('./index.linux-x64-gnu.node') } catch (e) { - loadError = e + loadErrors.push(e) } - break - case 'ia32': - localFileExisted = existsSync( - join(__dirname, 'index.win32-ia32-msvc.node') - ) try { - if (localFileExisted) { - nativeBinding = require('./index.win32-ia32-msvc.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-win32-ia32-msvc') + const binding = require('@databricks/databricks-sql-kernel-linux-x64-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-x64-gnu/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding } catch (e) { - loadError = e + loadErrors.push(e) } - break - case 'arm64': - localFileExisted = existsSync( - join(__dirname, 'index.win32-arm64-msvc.node') - ) + } + } else if (process.arch === 'arm64') { + if (isMusl()) { try { - if (localFileExisted) { - nativeBinding = require('./index.win32-arm64-msvc.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-win32-arm64-msvc') + return require('./index.linux-arm64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-arm64-musl') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm64-musl/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding } catch (e) { - loadError = e + loadErrors.push(e) } - break - default: - throw new Error(`Unsupported architecture on Windows: ${arch}`) - } - break - case 'darwin': - localFileExisted = existsSync(join(__dirname, 'index.darwin-universal.node')) - try { - if (localFileExisted) { - nativeBinding = require('./index.darwin-universal.node') } else { - nativeBinding = require('@databricks/databricks-sql-kernel-darwin-universal') - } - break - } catch {} - switch (arch) { - case 'x64': - localFileExisted = existsSync(join(__dirname, 'index.darwin-x64.node')) try { - if (localFileExisted) { - nativeBinding = require('./index.darwin-x64.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-darwin-x64') - } + return require('./index.linux-arm64-gnu.node') } catch (e) { - loadError = e + loadErrors.push(e) } - break - case 'arm64': - localFileExisted = existsSync( - join(__dirname, 'index.darwin-arm64.node') - ) try { - if (localFileExisted) { - nativeBinding = require('./index.darwin-arm64.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-darwin-arm64') + const binding = require('@databricks/databricks-sql-kernel-linux-arm64-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm64-gnu/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding } catch (e) { - loadError = e + loadErrors.push(e) } - break - default: - throw new Error(`Unsupported architecture on macOS: ${arch}`) - } - break - case 'freebsd': - if (arch !== 'x64') { - throw new Error(`Unsupported architecture on FreeBSD: ${arch}`) - } - localFileExisted = existsSync(join(__dirname, 'index.freebsd-x64.node')) - try { - if (localFileExisted) { - nativeBinding = require('./index.freebsd-x64.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-freebsd-x64') } - } catch (e) { - loadError = e - } - break - case 'linux': - switch (arch) { - case 'x64': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'index.linux-x64-musl.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-x64-musl.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-x64-musl') - } - } catch (e) { - loadError = e - } - } else { - localFileExisted = existsSync( - join(__dirname, 'index.linux-x64-gnu.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-x64-gnu.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-x64-gnu') - } - } catch (e) { - loadError = e + } else if (process.arch === 'arm') { + if (isMusl()) { + try { + return require('./index.linux-arm-musleabihf.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-arm-musleabihf') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm-musleabihf/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./index.linux-arm-gnueabihf.node') + } catch (e) { + loadErrors.push(e) } - break - case 'arm64': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'index.linux-arm64-musl.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-arm64-musl.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm64-musl') - } - } catch (e) { - loadError = e + try { + const binding = require('@databricks/databricks-sql-kernel-linux-arm-gnueabihf') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm-gnueabihf/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } - } else { - localFileExisted = existsSync( - join(__dirname, 'index.linux-arm64-gnu.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-arm64-gnu.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm64-gnu') - } - } catch (e) { - loadError = e + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'loong64') { + if (isMusl()) { + try { + return require('./index.linux-loong64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-loong64-musl') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-loong64-musl/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding + } catch (e) { + loadErrors.push(e) } - break - case 'arm': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'index.linux-arm-musleabihf.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-arm-musleabihf.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm-musleabihf') - } - } catch (e) { - loadError = e + } else { + try { + return require('./index.linux-loong64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-loong64-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-loong64-gnu/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } - } else { - localFileExisted = existsSync( - join(__dirname, 'index.linux-arm-gnueabihf.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-arm-gnueabihf.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm-gnueabihf') - } - } catch (e) { - loadError = e + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'riscv64') { + if (isMusl()) { + try { + return require('./index.linux-riscv64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-riscv64-musl') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-riscv64-musl/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } + return binding + } catch (e) { + loadErrors.push(e) } - break - case 'riscv64': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'index.linux-riscv64-musl.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-riscv64-musl.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-riscv64-musl') - } - } catch (e) { - loadError = e + } else { + try { + return require('./index.linux-riscv64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-riscv64-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-riscv64-gnu/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } - } else { - localFileExisted = existsSync( - join(__dirname, 'index.linux-riscv64-gnu.node') - ) - try { - if (localFileExisted) { - nativeBinding = require('./index.linux-riscv64-gnu.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-riscv64-gnu') - } - } catch (e) { - loadError = e + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'ppc64') { + try { + return require('./index.linux-ppc64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-ppc64-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-ppc64-gnu/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 's390x') { + try { + return require('./index.linux-s390x-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-linux-s390x-gnu') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-s390x-gnu/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`)) + } + } else if (process.platform === 'openharmony') { + if (process.arch === 'arm64') { + try { + return require('./index.openharmony-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-openharmony-arm64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-openharmony-arm64/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'x64') { + try { + return require('./index.openharmony-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-openharmony-x64') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-openharmony-x64/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm') { + try { + return require('./index.openharmony-arm.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@databricks/databricks-sql-kernel-openharmony-arm') + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-openharmony-arm/package.json').version + if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`)) + } + } else { + loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`)) + } +} + +function createLoadErrorChain(errors) { + return errors.reduce((previous, current) => { + let message + try { + message = + current && typeof current.message === 'string' + ? current.message + : String(current) + } catch { + message = 'Unknown error' + } + const error = new Error(message) + error.cause = previous + return error + }, null) +} + +// NAPI_RS_FORCE_WASI is a tri-state flag: +// unset / any other value → native binding preferred, WASI is only a fallback +// 'true' → prefer WASI, but retain native as a lazy fallback +// 'error' → require WASI without initializing a native fallback +// Treating any non-empty string as truthy (the historical behavior) meant +// NAPI_RS_FORCE_WASI=false, NAPI_RS_FORCE_WASI=0, etc. inadvertently triggered +// the WASI path, causing ENOENT for packages shipped without a .wasi.cjs file. +// +// NAPI_RS_WASI_FLAVOR selects one exact generated flavor and implies strict +// WASI loading. It never crosses into another flavor or falls back to native. +const __napiWasiFlavors = ["wasm32-wasi"] +const __napiWasiFlavor = process.env.NAPI_RS_WASI_FLAVOR +const __napiWasiFlavorRequested = + typeof __napiWasiFlavor === 'string' && __napiWasiFlavor.length > 0 +if ( + __napiWasiFlavorRequested && + __napiWasiFlavors.indexOf(__napiWasiFlavor) === -1 +) { + throw new Error( + 'Unsupported WASI flavor "' + + __napiWasiFlavor + + '". Available flavors: ' + + __napiWasiFlavors.join(', '), + ) +} +const forceWasiError = process.env.NAPI_RS_FORCE_WASI === 'error' +const forceWasi = + process.env.NAPI_RS_FORCE_WASI === 'true' || + forceWasiError || + __napiWasiFlavorRequested + +if (!forceWasi) { + nativeBinding = requireNative() +} + +if (!nativeBinding || forceWasi) { + let wasiBinding = null + let wasiBindingLoaded = false + const wasiBindingErrors = [] + const __napiWasiResolveCandidate = (specifier, isPackage, localArtifacts) => { + try { + require.resolve(specifier) + } catch (resolveError) { + if (!resolveError || resolveError.code !== 'MODULE_NOT_FOUND') { + throw resolveError + } + if (isPackage) { + try { + require.resolve(specifier + '/package.json') + } catch (packageError) { + if (packageError && packageError.code === 'MODULE_NOT_FOUND') { + return resolveError } + // An exports restriction proves the package exists even when its + // package.json is not public. Preserve the root resolution failure. + throw resolveError } - break - case 's390x': - localFileExisted = existsSync( - join(__dirname, 'index.linux-s390x-gnu.node') - ) + // The package exists but its main/export target is broken. + throw resolveError + } + return resolveError + } + if (localArtifacts) { + let artifactError = null + for (let i = 0; i < localArtifacts.length; i++) { try { - if (localFileExisted) { - nativeBinding = require('./index.linux-s390x-gnu.node') - } else { - nativeBinding = require('@databricks/databricks-sql-kernel-linux-s390x-gnu') + require.resolve(localArtifacts[i]) + return null + } catch (resolveError) { + if (!resolveError || resolveError.code !== 'MODULE_NOT_FOUND') { + throw resolveError + } + artifactError = resolveError + } + } + return artifactError + } + return null + } + if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === "wasm32-wasi")) { + let candidateError = null + let candidateFailed = false + try { + candidateError = __napiWasiResolveCandidate('./index.wasi.cjs', false, ["./index.wasm32-wasi.debug.wasm","./index.wasm32-wasi.wasm"]) + candidateFailed = candidateError !== null + if (!candidateFailed) { + wasiBinding = require('./index.wasi.cjs') + nativeBinding = wasiBinding + wasiBindingLoaded = true + } + } catch (err) { + candidateError = err + candidateFailed = true + } + if (candidateFailed) { + wasiBindingErrors.push(candidateError) + loadErrors.push(candidateError) + } + } + if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === "wasm32-wasi")) { + let candidateError = null + let candidateFailed = false + try { + candidateError = __napiWasiResolveCandidate('@databricks/databricks-sql-kernel-wasm32-wasi', true, undefined) + candidateFailed = candidateError !== null + if (!candidateFailed) { + if (process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + const bindingPackageVersion = require('@databricks/databricks-sql-kernel-wasm32-wasi/package.json').version + if (bindingPackageVersion !== '1.4.0') { + throw new Error(`WASI binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) } - } catch (e) { - loadError = e } - break - default: - throw new Error(`Unsupported architecture on Linux: ${arch}`) + wasiBinding = require('@databricks/databricks-sql-kernel-wasm32-wasi') + nativeBinding = wasiBinding + wasiBindingLoaded = true + } + } catch (err) { + candidateError = err + candidateFailed = true } - break - default: - throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`) + if (candidateFailed) { + wasiBindingErrors.push(candidateError) + loadErrors.push(candidateError) + } + } + if ( + !wasiBindingLoaded && + forceWasi && + !forceWasiError && + !__napiWasiFlavorRequested + ) { + nativeBinding = requireNative() + } + if ((forceWasiError || __napiWasiFlavorRequested) && !wasiBindingLoaded) { + const error = new Error( + __napiWasiFlavorRequested + ? 'WASI binding for flavor "' + __napiWasiFlavor + '" not found' + : 'WASI binding not found and NAPI_RS_FORCE_WASI is set to error', + ) + error.cause = createLoadErrorChain(wasiBindingErrors) + throw error + } } if (!nativeBinding) { - if (loadError) { - throw loadError + if (loadErrors.length > 0) { + const error = new Error( + `Cannot find native binding. ` + + `npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). ` + + 'Please try `npm i` again after removing both package-lock.json and node_modules directory.', + ) + // assign instead of the `new Error(message, { cause })` options form, + // which Node < 16.9 silently ignores + error.cause = createLoadErrorChain(loadErrors) + throw error } throw new Error(`Failed to load native binding`) } -const { AsyncStatement, AsyncResultHandle, CancellableExecution, Connection, AuthMode, openSession, initKernelLogging, kernelLoggingStats, setKernelLogLevel, Statement, version } = nativeBinding - -module.exports.AsyncStatement = AsyncStatement -module.exports.AsyncResultHandle = AsyncResultHandle -module.exports.CancellableExecution = CancellableExecution -module.exports.Connection = Connection -module.exports.AuthMode = AuthMode -module.exports.openSession = openSession -module.exports.initKernelLogging = initKernelLogging -module.exports.kernelLoggingStats = kernelLoggingStats -module.exports.setKernelLogLevel = setKernelLogLevel -module.exports.Statement = Statement -module.exports.version = version +module.exports = nativeBinding +module.exports.AsyncResultHandle = nativeBinding.AsyncResultHandle +module.exports.AsyncStatement = nativeBinding.AsyncStatement +module.exports.CancellableExecution = nativeBinding.CancellableExecution +module.exports.Connection = nativeBinding.Connection +module.exports.Statement = nativeBinding.Statement +module.exports.AuthMode = nativeBinding.AuthMode +module.exports.initKernelLogging = nativeBinding.initKernelLogging +module.exports.kernelLoggingStats = nativeBinding.kernelLoggingStats +module.exports.openSession = nativeBinding.openSession +module.exports.setKernelLogLevel = nativeBinding.setKernelLogLevel +module.exports.version = nativeBinding.version diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index a3a17f2e..96f988f2 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -1149,13 +1149,15 @@ impl StreamingCloudFetchProvider { // first refusal refreshes at once; if a refreshed URL is refused // too, fall through to the backoff below before refreshing again. if let Some(status @ (401 | 403 | 404)) = e.http_status { - debug!( - "Chunk {} download got HTTP {}; refreshing the link before retry", - chunk_index, status, - ); rejected_url = Some(link.url.clone()); if !refused_before { refused_before = true; + // Later refusals are logged by the retry warning below. + warn!( + "Chunk {} download refused with HTTP {} (attempt {}/{}): {}, \ + refreshing the link", + chunk_index, status, attempts, ctx.max_retries, e + ); continue; } } From 1ceef67d0d8944b197f887fdcfcbd35f9a1c4212 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sun, 15 Nov 2026 08:53:24 +0000 Subject: [PATCH 09/11] chore(napi): restore the generated bindings cb4b6ac accidentally committed napi/index.js and napi/index.d.ts regenerated by a local napi-rs build. Restore them to main's content; this PR does not change the bindings. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- napi/index.d.ts | 1801 +++++++++++++++++++++++------------------------ napi/index.js | 918 +++++++----------------- 2 files changed, 1150 insertions(+), 1569 deletions(-) diff --git a/napi/index.d.ts b/napi/index.d.ts index 1f1d3581..bcb54502 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -1,806 +1,362 @@ -/* auto-generated by NAPI-RS */ +/* tslint:disable */ /* eslint-disable */ -/** - * Opaque result-fetch handle returned by - * `AsyncStatement.awaitResult()`. Wraps a kernel `ResultStream` - * directly; structurally analogous to the sync `Statement`'s - * fetch-side surface (`fetchNextBatch` / `schema` / - * `statementId`). - * - * `cancel()` / `close()` are not exposed: the parent - * `AsyncStatement` owns server-side lifecycle. A `close()` here - * would create dual-ownership of the same statement_id with - * inconsistent close semantics. Callers `close()` the parent - * `AsyncStatement` after they're done fetching. - * - * Schema is cached at construction so it survives the underlying - * stream being drained; mirrors the sync `Statement.schema()` - * post-close contract. - */ -export declare class AsyncResultHandle { - /** - * Server-issued statement id. Cached at construction; readable - * for log correlation. Matches the parent `AsyncStatement`'s - * `statementId`. - */ - get statementId(): string - /** - * Pull the next batch of results. Returns `null` when the - * stream is exhausted. The returned `ArrowBatch.ipcBytes` is a - * complete Arrow IPC stream (schema header + 1 record-batch - * message), suitable for handing to `apache-arrow`'s - * `RecordBatchReader`. Byte-identical to the sync - * `Statement.fetchNextBatch()` payload for the same query. - */ - fetchNextBatch(): Promise - /** - * Result schema as an Arrow IPC payload (schema header only, - * no record-batch message). Available before any batches have - * been fetched. Sync because the body has no `.await` — - * `encode_ipc_stream` is pure CPU work over the cached - * `Arc`. - */ - schema(): ArrowSchema -} + +/* auto-generated by NAPI-RS */ /** - * Opaque async-statement handle. + * Per-statement options for `Connection.executeStatement`. * - * Returned by `Connection.submitStatement(...)` after the kernel - * `Statement::submit()` returns (server sent `wait_timeout=0s`, so - * the response carries a `statement_id` but the statement is still - * `Pending`/`Running`). JS drives polling via `status()` / - * `awaitResult()`. + * Mirrors the kernel `StatementSpec` knobs that are safe to thread + * through napi without a kernel-side change. Today this covers: + * - `statementConf` — per-statement Spark conf overlay + * (`StatementSpec.statement_conf` → SEA `parameters` / + * Thrift `confOverlay`) + * - `queryTags` — convenience wrapper over `statementConf` with + * key `query_tags`; serialised to the same comma-separated + * `key:value` wire shape NodeJS Thrift's `serializeQueryTags` + * produces (`lib/utils/queryTags.ts`). Backslashes in keys are + * doubled; backslash/colon/comma in values are backslash-escaped. * - * Concurrency shape: `status()`, `awaitResult()`, and `close()` take - * `inner.lock()` and hold the guard across the kernel `.await` (tokio - * `Mutex` is FIFO), so `status()` / `close()` queue behind any - * in-flight `awaitResult()` until it returns naturally. `cancel()` is - * the deliberate exception: it does **not** touch `inner` — it fires - * through the detached `AsyncStatementCanceller` (session + - * statement_id, captured at construction), so an explicit - * `stmt.cancel()` interrupts an in-flight `awaitResult()` instead of - * queueing behind it. The server-side cancel flips the statement - * terminal, which the parked `awaitResult()` poll loop observes - * (`Cancelled`) and returns on. The kernel's `AwaitResultCancelGuard` - * still covers the drop-cancel case (Promise.race / timeout) - * independently — see module docs. + * `rowLimit` (SEA `row_limit`) is exposed here and threaded onto the kernel + * `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`) + * carry bound query parameters, decoded via `params::parse_typed_value`. + * `rawParams` forwards pre-marshalled SEA parameters unchanged. + * (There is no `queryTimeoutSecs`: it abused the SEA `wait_timeout` inline-hold + * window and was removed — a real per-statement timeout is `STATEMENT_TIMEOUT`.) + * + * **Tag-order caveat (M4 parity note).** The napi `queryTags` field + * is a Rust `HashMap` whose iteration order is + * non-deterministic, so the serialised `query_tags` value may have + * a different key order than Thrift's `serializeQueryTags` (which + * iterates `Object.keys(...)` in insertion order) for the same + * input. The SEA server is order-insensitive on conf values, so + * the two are functionally equivalent. If a caller needs + * byte-identical Thrift parity, the JS adapter pre-serialises via + * `serializeQueryTags` and writes the result into + * `statementConf["query_tags"]` directly — see + * `KernelSessionBackend.executeStatement` in the NodeJS driver. This + * path is the one the production code uses. */ -export declare class AsyncStatement { +export interface ExecuteOptions { /** - * Server-issued statement id. Cached at construction; readable - * even after `close()` so JS-side log lines can correlate - * against kernel / server logs which key on the same id. + * Per-statement Spark conf overlay. Merged on top of the + * session-level `sessionConf` at execute time; this map wins + * on key collisions. Unknown keys are rejected by the server. */ - get statementId(): string + statementConf?: Record /** - * One-shot status check. Returns a string enum matching the - * kernel `StatementStatus` shape: - * `'Pending' | 'Running' | 'Succeeded' | 'Failed' | - * 'Cancelled' | 'Closed' | 'Unknown'`. (`'Unknown'` is the - * `#[non_exhaustive]` forward-compat catch-all that - * `StatementStatus::as_str` can return — consumers switching on - * the state must handle it.) Returns - * `KernelError(InvalidStatementHandle)` if the statement has - * been explicitly `close()`d. + * Query tags as key→value pairs. Serialised to a comma- + * separated `key:value` string (backslash-escaping `\`, `:`, + * `,`) and placed into `statementConf["query_tags"]`, matching + * NodeJS Thrift's `serializeQueryTags` wire shape. Passing + * both `queryTags` AND a `query_tags` key in `statementConf` + * raises `InvalidArgument` — the caller's intent is ambiguous + * so we refuse to silently pick one over the other. * - * The `Failed` variant collapses to the string `'Failed'` on - * the JS side; the underlying error envelope (sql_state / - * error_code / query_id) is surfaced by `awaitResult()`'s - * rejection, which is where callers actually need the typed - * error. `status()` is intended for polling progress UIs - * that only need the state name. + * A **`null`** value emits a **bare key** (no colon) — e.g. + * `{ production: null }` → `"production"` — matching the + * connectors' `key`-only tag form. + * + * See the struct-level "Tag-order caveat" for the + * HashMap-iteration-order vs `Object.keys`-iteration-order + * divergence and the byte-identical-Thrift-parity workaround. */ - status(): Promise - /** Rows modified by the statement (UPDATE / INSERT / DELETE / MERGE). */ - numModifiedRows(): Promise + queryTags?: Record /** - * Server-supplied user-facing message (may contain SQL fragments — - * redact before centralised logging). + * Server-side cap on the number of rows this statement returns + * (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to + * `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. */ - displayMessage(): Promise - /** Server-supplied diagnostic detail. */ - diagnosticInfo(): Promise - /** Server-supplied structured error detail (JSON), when enabled. */ - errorDetailsJson(): Promise + rowLimit?: number /** - * Block until the server reaches a terminal state, then return - * an `AsyncResultHandle` that wraps the materialised result - * stream. The handle exposes `fetchNextBatch()` / `schema()` - * for consuming the result, plus `statementId` for log - * correlation. - * - * Drop-cancel safety: kernel `await_result` installs - * `AwaitResultCancelGuard` which fires a fire-and-forget - * `cancel_statement` if the future is dropped mid-poll - * (timeout, tokio::select! loser, JS-side `Promise.race` - * loser). The `util::guarded` `catch_unwind` here covers the - * V8-panic-across-boundary case on top. Returns - * `KernelError(InvalidStatementHandle)` if the statement has - * been explicitly `close()`d. + * Positional parameters, in 1-based wire order. Index `i` in this + * Vec corresponds to the `i+1`-th `?` placeholder in the SQL. + * Each entry is a `{ sqlType, value }` pair — `value` is the + * string-encoded literal or `null` for SQL NULL. Mirrors + * `StatementSpec::positional_params`; decoded via [`parse_typed_value`]. */ - awaitResult(): Promise + positionalParams?: Array /** - * Server-side cancel. Returns - * `KernelError(InvalidStatementHandle)` if the statement has - * been explicitly `close()`d. Idempotent against a server - * that already reached a terminal state — the kernel's - * `cancel_statement` is a no-op there. - * - * **Lock-free by design.** Unlike `status()` / `awaitResult()` / - * `close()`, this does not take `inner.lock()` — it fires through - * the detached `AsyncStatementCanceller` captured at construction. - * That lets `stmt.cancel()` interrupt an in-flight `awaitResult()` - * (which holds the mutex for the whole poll) instead of queueing - * behind it: the server-side cancel flips the statement terminal, - * the parked `awaitResult()` poll loop observes `Cancelled` and - * returns. The closed-state check reads a lock-free flag so a - * cancel after an explicit `close()` still surfaces - * `InvalidStatementHandle`. + * Named parameters (`:name` placeholders). Each carries its `name` + * alongside the `{ sqlType, value? }` pair. Mapped to a kernel + * `TypedValue` via the same [`parse_typed_value`] codec and bound with + * `StatementSpec::param_named`. Named is the SEA-spec-required public + * param form (`StatementParameter.name` is `openapi_required`); + * positional is the documented-undocumented variant. The two are + * mutually exclusive at the SQL level (`?` vs `:name`). */ - cancel(): Promise + namedParams?: Array /** - * Explicit close. Idempotent — a second call on an - * already-closed handle returns `Ok(())`. On `Err`, the napi - * inner is already `None`, so a JS-side retry sees the - * closed-handle short-circuit and returns `Ok(())` without - * re-attempting the wire call. The kernel's own `Drop` - * fire-and-forget retry runs once in the background. + * Pre-marshalled parameters passed through `StatementSpec::param_raw`. + * Omit `name` for positional values. Raw parameters cannot be mixed with + * typed parameters or combine named and positional markers. */ - close(): Promise + rawParams?: Array } - /** - * Handle returned by `Connection.executeStatementCancellable`. Owns the - * built-but-not-yet-executed kernel `Statement` plus a detached - * [`StatementCanceller`] captured before dispatch, so JS can fire a - * server-side cancel while the blocking `result()` is in flight. + * A named bound parameter — a [`TypedValueInput`] plus its `:name`. Kept a + * distinct napi object (rather than an optional `name` on `TypedValueInput`) + * so the positional surface stays a clean ordered list with no name field. + */ +export interface NamedTypedValueInput { + name: string + sqlType: string + value?: string +} +/** + * Authentication mode selector crossing the napi boundary. The string + * literals are what napi-rs emits from this `#[napi(string_enum)]` — the + * NodeJS SEA adapter (`KernelAuth`) matches them verbatim (`'Pat'`, + * `'OAuthM2m'`, `'OAuthU2m'`, `'AzureSpM2m'`). * - * `pending` is `Arc>>` so `result()` can - * `.take()` the statement (the kernel `execute()` borrows it `&mut`, - * then it moves into the produced `Statement` wrapper to keep its - * `ValidityFlag` set — see `statement.rs`). A second `result()` call - * after the first resolved surfaces `InvalidStatementHandle`. + * Mirrors the kernel [`AuthConfig`] variants this binding supports. + * `OAuthFederation` / `External` are intentionally not exposed yet — the + * kernel marks federation as not-yet-implemented and `External` is a + * Rust-trait escape hatch with no JS-callback bridge. */ -export declare class CancellableExecution { +export const enum AuthMode { + /** Personal access token (`token`). */ + Pat = 'Pat', + /** OAuth 2.0 machine-to-machine — `oauthClientId` + `oauthClientSecret`. */ + OAuthM2m = 'OAuthM2m', /** - * The server-issued statement id this execution targets, if the - * server has issued one yet (`null` before the initial submit - * round-trip publishes it mid-`result()`). Useful for log - * correlation while the blocking drive is in flight. + * OAuth 2.0 machine-to-machine with a JWT private-key client + * assertion — `oauthClientId` + `jwtKeyFile` + `jwtKid`. */ - get statementId(): string | null + OAuthM2mJwt = 'OAuthM2mJwt', /** - * Drive the blocking `execute()` and resolve to a `Statement` - * (identical to what `executeStatement` returns) once the kernel - * reaches a terminal state and the result stream is ready. - * - * Consumes the pending statement: a second `result()` call returns - * `KernelError(InvalidStatementHandle)`. The future is - * drop-cancel-safe — the kernel's per-execute `MidExecuteCancelState` - * guard fires a fire-and-forget `cancel_statement` if this future is - * dropped mid-flight (`Promise.race` / timeout loser), independently - * of an explicit `cancel()`. - * - * On a server-side cancel the kernel's blocking `execute()` currently - * surfaces `InvalidArgument` (a known kernel quirk — the async path - * returns `Cancelled`). When this handle's `cancel()` actually dispatched a - * server-side cancel, we normalise that into `Cancelled` here so JS callers - * can rely on a single cancelled-status code regardless of execution path. - * - * Three outcomes can race the blocking drive: (1) a natural terminal state - * → `Ok` or the genuine error; (2) an explicit `cancel()` that dispatched a - * server cancel → this `result()` rejects with a `Cancelled`-coded error - * (the normalisation above); (3) the future being **dropped** mid-flight - * (`Promise.race`/timeout loser) → the kernel's `MidExecuteCancelState` - * drop-guard fires a fire-and-forget `cancel_statement`, but there is no - * `result()` left to observe a code. Only (2) yields a `Cancelled` error. + * OAuth 2.0 user-to-machine (browser flow) — optional `oauthClientId` + * + `oauthRedirectPort`. */ - result(): Promise + OAuthU2m = 'OAuthU2m', /** - * Server-side cancel of the in-flight statement. - * - * Lock-free: fires the detached `StatementCanceller` captured at - * construction rather than taking the mutex `result()` holds, so it - * interrupts a still-running blocking `result()` instead of queueing - * behind it. No-op (returns `Ok`) if `result()` already finished - * successfully, or if no statement id has been observed yet (query still - * in its initial submit round-trip), and idempotent against a server - * already in a terminal state. + * Azure Entra service-principal M2M — `azureClientId` + + * `azureClientSecret` (+ optional `azureTenantId` / + * `azureWorkspaceResourceId`). The kernel builds the Entra token + * endpoint + `.default` scope, auto-discovers the tenant from the + * workspace when `azureTenantId` is omitted, and — when + * `azureWorkspaceResourceId` is set — additionally sends the SP + * management token for an RBAC-only service principal. */ - cancel(): Promise + AzureSpM2m = 'AzureSpM2m' } - /** - * Opaque connection handle wrapping a kernel `Session`. + * A single extra HTTP header as an explicit `{ name, value }` pair. * - * `inner` is `Arc>>` so: - * - the Drop impl can clone the `Arc` and `.take()` the session on a - * background tokio task without holding `&mut self` (which Drop is - * forbidden from doing across an `await`), - * - `close()` can `.take()` the session to consume it for the kernel's - * move-by-value `Session::close(self)` signature. + * An ordered list of these (`ConnectionOptions.custom_headers`) mirrors + * the kernel core's `Vec<(String, String)>` and the pyo3 binding's + * `http_headers`: order is preserved and duplicate `name`s are allowed. + * A struct (rather than a raw `[name, value]` tuple) because napi-rs + * does not marshal Rust tuples through `#[napi(object)]` fields; the + * struct is the idiomatic, self-documenting equivalent and maps to a JS + * `{ name: string, value: string }`. + */ +export interface HeaderEntry { + name: string + value: string +} +/** + * Programmatic HTTP/HTTPS proxy configuration, mirroring the kernel's + * internal [`ProxyConfig`]. Supplied as a structured object rather than a + * flattened URL so credentials never have to be percent-encoded into the URL + * and the bypass-host list can be expressed. * - * **Concurrency shape** — both `executeStatement` and - * `submitStatement` build the kernel `Statement` under `inner.lock()` - * and then RELEASE the guard before the wire call - * (`stmt.execute().await` / `stmt.submit().await`). `Session::statement()` - * is `&self`-callable and only clones the session's internal `Arc`, so - * the built statement is independent of the guard. Concurrent - * `Promise.all([executeStatement(q1), submitStatement(q2)])` therefore - * serialise only for the microsecond statement-build, not the network - * round-trip, and `close()` never blocks behind an in-flight execute or - * submit. See - * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. + * - `url` — proxy endpoint, e.g. `"http://proxy.corp.example.com:8080"`. Must + * use the `http://` or `https://` scheme. + * - `username` / `password` — optional proxy basic-auth, applied via + * `reqwest`'s `Proxy::basic_auth` (not embedded in the URL). + * - `bypassHosts` — optional comma-separated host/domain list that should + * bypass the proxy (e.g. `"localhost,*.internal.corp"`). */ -export declare class Connection { +export interface ProxyInput { + url: string + username?: string + password?: string + bypassHosts?: string +} +/** + * JS-visible options for opening a Databricks SQL session. + * + * Authentication is selected by `authMode` (default [`AuthMode::Pat`]): + * - `Pat` — `token` required. + * - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required. + * - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional + * (defaults to the `databricks-sql-connector` client on port 8030). + * - `AzureSpM2m` — `azureClientId` + `azureClientSecret` required + * (+ optional `azureTenantId` / `azureWorkspaceResourceId`). + * + * Catalog / schema / sessionConf are applied once at session creation + * and remain in effect for every statement run on the resulting + * `Connection`. The SEA wire protocol carries them on + * `CreateSession`, not on `ExecuteStatement` — so there is no + * per-statement override path on this binding. + */ +export interface ConnectionOptions { /** - * Server-issued session id. Cached at construction; readable - * even after `close()` so JS-side log lines can correlate - * against kernel / server logs which key on the same id. + * Workspace host, e.g. `adb-…azuredatabricks.net`. The kernel + * normalises this — bare hostnames get `https://` prepended. */ - get sessionId(): string + hostName: string /** - * Execute a SQL statement and return a Statement handle that - * streams batches via `fetchNextBatch()`. - * - * Catalog / schema / sessionConf are session-level - * (`openSession`). Per-statement options on `ExecuteOptions`: - * - `statementConf` — per-statement Spark conf overlay - * - `queryTags` — serialised to a comma-separated `key:value` - * string and placed in `statement_conf["query_tags"]`, - * matching NodeJS Thrift's `serializeQueryTags` wire shape - * - * `options` is omitted/`None` for the no-options path; passing - * `{ statementConf: {} }` (an empty map) is treated the same as - * omission to keep the wire shape stable for the common case. + * JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The + * kernel parses out the warehouse id. */ - executeStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise + httpPath: string /** - * directResults execute — the Thrift/JDBC model. Sends ExecuteStatement - * with no `wait_timeout` field (server applies its ~10s default inline wait - * and auto-closes on success) and returns WITHOUT polling past it: - * - * - a **`Statement`** (left arm) when the query finished within the inline - * wait — terminal, result ready inline, `close()` is a clean release; - * - an **`AsyncStatement`** (right arm) when it did not — a poll/cancel - * handle the caller drives (`status()` / `awaitResult()` / `cancel()`). - * - * JS distinguishes the arms by feature-detecting `awaitResult` (present - * only on `AsyncStatement`). This is the path that gives mid-run cancel for - * long queries WITHOUT the eager-handle / close-drives workaround: the - * returned handle always corresponds to a server-owned statement. - * - * **Load-bearing contract:** the kernel's `DirectStatement::{Completed, - * Running}` discriminant cannot ride on these opaque `#[napi]` classes, so - * consumers MUST feature-detect via `awaitResult` (the only member unique to - * `AsyncStatement`). `Statement` (the Completed arm) MUST NOT gain an - * `awaitResult` member, or every consumer silently misroutes. The pyo3 - * binding makes the same `await_result`-probe assumption. + * Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat: + * existing PAT callers pass only `token`). */ - executeStatementDirect(sql: string, options?: ExecuteOptions | undefined | null): Promise + authMode?: AuthMode /** - * Execute a SQL statement on the blocking (sync) path, but return a - * `CancellableExecution` handle so a concurrent JS task can cancel - * the query *while it is still running server-side*. - * - * `executeStatement` builds the kernel `Statement`, awaits the - * blocking `execute()`, and only then hands JS a `Statement` — so a - * query that runs for several seconds is uncancellable from JS on - * that path (there is no handle until the blocking call resolves). - * This method instead builds the statement, captures a detached - * `StatementCanceller` **before** dispatching `execute()`, and hands - * JS a `CancellableExecution` immediately. The caller drives the - * blocking execution via `result()` (resolves to the same - * `Statement` `executeStatement` returns) and can fire `cancel()` - * concurrently to interrupt a still-running query mid-COMPUTE. - * - * Option semantics are identical to `executeStatement`. - * Mirrors the pyo3 `Statement.canceller()` / `Statement.execute()` - * split (PR #121): obtain the canceller before the blocking drive. + * Personal access token. Required (and non-empty) for + * [`AuthMode::Pat`]; ignored otherwise. */ - executeStatementCancellable(sql: string, options?: ExecuteOptions | undefined | null): Promise + token?: string /** - * Submit a SQL statement and return immediately with an - * `AsyncStatement` handle, without blocking until the query - * finishes. The kernel's `Statement::submit()` sends - * `wait_timeout=0s`, so the server responds as soon as it has a - * `statement_id` (state `Pending`/`Running`); JS drives polling - * via `AsyncStatement.status()` and materialises results with - * `AsyncStatement.awaitResult()`. - * - * This is the async-execution path the Thrift backend always - * uses (`runAsync: true`): the SEA backend submits, returns a - * pending operation handle, and polls to terminal during - * fetch. Option semantics (statementConf / queryTags / - * rowLimit / positional + named params) match `executeStatement`. - * Submit always sends `wait_timeout=0s` so the call returns - * immediately; the caller drives completion via `status()` / - * `awaitResult()`. Only the blocking-vs-pending return contract - * differs from `executeStatement`. + * OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for + * [`AuthMode::OAuthU2m`] (defaults to `databricks-sql-connector`). */ - submitStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise + oauthClientId?: string + /** OAuth client secret. Required for [`AuthMode::OAuthM2m`]. */ + oauthClientSecret?: string /** - * Explicit close. Awaits the server-side `DeleteSession` so the - * JS caller can observe failures (auth revoked mid-session, - * warehouse stopped, network error). Idempotent — a second call - * on an already-closed connection returns `Ok`. - * - * **Errors are terminal from the JS side.** The kernel session - * handle is consumed (`take()`) BEFORE the wire `DeleteSession` - * runs, because `Session::close` takes `self` by value. On `Err`, - * the napi `inner` is already `None`, so a JS-side retry sees a - * closed connection and returns `Ok(())` without re-attempting - * the wire call. The kernel's own `Drop` fire-and-forget retry - * runs once in the background — the JS caller can log the error - * but cannot drive a retry. If you need retry-on-failure - * semantics for `DeleteSession`, layer them above this method. + * Localhost callback port for the [`AuthMode::OAuthU2m`] browser + * flow. Omitted ⇒ kernel default (8030). */ - close(): Promise + oauthRedirectPort?: number /** - * All catalogs visible to the session. - * - * JDBC `getCatalogs` shape: `TABLE_CAT: Utf8`. + * OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults + * (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M). */ - listCatalogs(): Promise + oauthScopes?: Array /** - * Schemas filtered by catalog (exact) and schema name pattern. An empty - * catalog matches nothing; non-empty catalogs remain exact identifiers. - * - * JDBC `getSchemas` shape: `TABLE_SCHEM, TABLE_CATALOG`. + * OAuth token endpoint override. When omitted the kernel discovers the + * endpoint via the workspace's OIDC configuration. Set it to point the + * client-credentials / JWT client-assertion grant at the workspace's + * configured IdP token endpoint (e.g. Entra ID for Azure Databricks), + * which is required when that IdP — not Databricks-native OIDC — is the + * authority for [`AuthMode::OAuthM2m`] / [`AuthMode::OAuthM2mJwt`]. */ - listSchemas(catalog?: string | undefined | null, schemaPattern?: string | undefined | null): Promise + tokenUrl?: string /** - * Tables filtered by catalog (**pattern**), schema (pattern), table - * (pattern). - * - * The catalog is an ODBC/JDBC LIKE pattern (`%` / `_`), matching - * Thrift `getTables`: a wildcard catalog matches multiple catalogs; - * a literal name (or an escaped `\_` / `\%`) takes the fast exact - * path. `undefined`/omitted catalog means "all catalogs", while an - * **empty string** means "match nothing" (zero rows) — pass - * `undefined`, not `""`, for all catalogs. The catalog pattern is - * validated (whitespace-only / NUL / >255 bytes are rejected with an - * error). - * - * JDBC `getTables` shape: 10 columns. `tableTypes`, when provided, - * filters rows by `TABLE_TYPE` kernel-side. - * - * `tableTypes` is an advisory filter. Databricks `SHOW TABLES` does - * NOT honour the table-type filter server-side; the kernel applies - * it client-side after the result returns. Callers expecting - * server-side rejection of off-type tables should not rely on this. + * U2M on-disk token-cache control (kernel path). Omitted ⇒ the kernel + * default (cache enabled, encrypted under a machine-local key, survives + * restarts). `false` disables on-disk persistence (re-login each fresh + * process); `true` keeps it enabled. Applies to [`AuthMode::OAuthU2m`]. */ - listTables(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, tableTypes?: Array | undefined | null): Promise + tokenCacheEnabled?: boolean /** - * Columns of tables matching the filter. An empty catalog matches - * nothing; non-empty catalogs remain exact identifiers. - * - * JDBC `getColumns` shape: 23 columns. + * Optional passphrase for the U2M on-disk token cache (AES-256 key). + * Omitted/blank ⇒ a machine-local derived key. Supplying one is stronger. + * A passphrase with no explicit `tokenCacheEnabled` implies enabled. + * Applies to [`AuthMode::OAuthU2m`]. */ - listColumns(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, columnPattern?: string | undefined | null): Promise + tokenCachePassphrase?: string /** - * Functions visible to the session. An empty `catalog` is forwarded to - * SEA for native `GetFunctions`; `schemaPattern` and `functionPattern` are SQL LIKE. - */ - listFunctions(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, functionPattern?: string | undefined | null): Promise - /** - * Procedures visible to the session. `catalog` is exact; - * `schemaPattern` and `procedurePattern` are SQL LIKE. + * Path to the PEM private-key file. Required for + * [`AuthMode::OAuthM2mJwt`]. */ - listProcedures(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, procedurePattern?: string | undefined | null): Promise + jwtKeyFile?: string + /** JWT key id (`kid`). Required for [`AuthMode::OAuthM2mJwt`]. */ + jwtKid?: string /** - * All table types (`TABLE`, `VIEW`, `SYSTEM TABLE`, …). - * No wire call — static in-memory result. + * Passphrase for an encrypted PKCS#8 key. Optional for + * [`AuthMode::OAuthM2mJwt`] (omit for an unencrypted key). */ - listTableTypes(): Promise + jwtPassphrase?: string /** - * SQL data types supported by the workspace. - * No wire call — static in-memory result. + * JWT signing algorithm (`RS256`/`384`/`512`, `PS256`/`384`/`512`, + * `ES256`, `ES384`). Optional for [`AuthMode::OAuthM2mJwt`] + * (omitted ⇒ kernel default `RS256`). */ - listTypeInfo(): Promise + jwtAlgorithm?: string /** - * Primary keys for the given table. All three identifiers are - * exact — ODBC `SQLPrimaryKeys` does not support patterns. + * SP-wide Workload Identity Federation client id used during mandatory + * token exchange. Omitted selects BYOT / account-wide WIF. */ - getPrimaryKeys(catalog: string | undefined | null, schema: string | undefined | null, table: string): Promise + identityFederationClientId?: string /** - * Foreign-key relationships. The parent side is optional. When the - * foreign table is omitted, returns an empty result without issuing a - * server statement. When it is provided, its catalog and schema are - * required. All identifiers are exact — no LIKE patterns. + * Azure Entra app-registration client id. Required for + * [`AuthMode::AzureSpM2m`]; ignored otherwise. */ - getCrossReference(parentCatalog?: string | undefined | null, parentSchema?: string | undefined | null, parentTable?: string | undefined | null, foreignCatalog?: string | undefined | null, foreignSchema?: string | undefined | null, foreignTable?: string | undefined | null): Promise -} - -/** - * Opaque executed-statement handle. - * - * **Current concurrency shape** — every method takes `inner.lock()` - * and holds the guard across the kernel `.await`. tokio `Mutex` is - * FIFO, so cancel/close queue behind any in-flight `fetchNextBatch` - * until it returns naturally. This is a known limitation that exists - * because the napi shape has not yet been split into an - * `Arc` (for cancel/close, which the - * kernel exposes as `&self`-callable) plus a `Mutex>` only - * for the borrowed-mut fetch path. The lock-shape refactor needs a - * small kernel-side accessor and lands in a follow-up PR — see - * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. - * - * `schema` and `statement_id` are cached at construction so they - * survive `close()` — JS callers building error reports against a - * disposed statement can still read them. - */ -export declare class Statement { + azureClientId?: string /** - * Server-issued statement id. Cached at construction; readable - * even after `close()` so JS-side log lines can correlate against - * kernel / server logs which key on the same id. + * Azure Entra app-registration client secret. Required for + * [`AuthMode::AzureSpM2m`]. */ - get statementId(): string + azureClientSecret?: string /** - * Number of rows modified by the statement (UPDATE / INSERT / - * DELETE / MERGE). `null` for SELECT and on warehouses that don't - * surface the counter. Mirrors Thrift's - * `TGetOperationStatusResp.numModifiedRows`. + * Azure Entra tenant id. Optional for [`AuthMode::AzureSpM2m`]; + * omitted ⇒ the kernel auto-discovers it from the workspace's + * `/aad/auth` redirect (matching the Thrift connector). */ - numModifiedRows(): Promise + azureTenantId?: string /** - * Server-supplied user-facing message. Mirrors Thrift's - * `TGetOperationStatusResp.displayMessage`. **PII / sensitive- - * data note:** may contain SQL fragments or parameter values — - * redact before centralised logging. - * - * Populated on `Succeeded` / `Closed` paths (incl. an empty `Closed`). - * On terminal-error states (`Failed` / `Cancelled`) the kernel returns - * an Error instead of a `Statement`, and the same field rides on the JS - * Error envelope under the same `displayMessage` key. + * Azure workspace ARM resource id. Optional for [`AuthMode::AzureSpM2m`]; + * when set the kernel also sends the SP management token + * (`X-Databricks-Azure-SP-Management-Token`) + the + * `X-Databricks-Azure-Workspace-Resource-Id` header, so a service + * principal with an Azure RBAC role but no workspace membership can + * authenticate. Omitted ⇒ the data token authenticates alone. */ - displayMessage(): Promise + azureWorkspaceResourceId?: string /** - * Server-supplied diagnostic detail — multi-line operator / - * stack context. Mirrors Thrift's - * `TGetOperationStatusResp.diagnosticInfo`. For support surfaces, - * not user-facing. Same reachability + PII caveats as - * `displayMessage`. + * Default catalog for statements executed on this session. + * Routed through the kernel's `DefaultOpts` and onto the SEA + * `CreateSession.catalog` wire field. */ - diagnosticInfo(): Promise + catalog?: string /** - * Server-supplied JSON blob with extended error details. Mirrors - * Thrift's `TGetOperationStatusResp.errorDetailsJson`. - * Pass-through string — JS callers parse with `JSON.parse` if - * they need structured access. - * - * **Server-side gating:** populated only when the workspace has - * `spark.databricks.sql.errorDetailsJson.enabled = true` on the - * underlying SQL cluster. The flag is internal-only / default- - * false in the Databricks runtime, so for most JS callers this - * will return `null`. Admin-enabled workspaces return content - * shaped like `{"errorClass": "...", "messageTemplate": "..."}`. - * - * **Unbounded:** when populated, server can return a multi-MB - * blob; size before logging. + * Default schema for statements executed on this session. + * Routed through the kernel's `DefaultOpts` and onto the SEA + * `CreateSession.schema` wire field. */ - errorDetailsJson(): Promise + schema?: string /** - * Pull the next batch of results. Returns `null` when the stream - * is exhausted. The returned `ArrowBatch.ipcBytes` is a complete - * Arrow IPC stream (schema header + 1 record-batch message) - * suitable for handing to `apache-arrow`'s `RecordBatchReader`. - * - * On `Err`, the stream is in an unspecified state — call - * `close()` and discard the `Statement`. Subsequent - * `fetchNextBatch()` calls after an error are not guaranteed to - * succeed or fail consistently. + * Server-bound session conf (Spark conf, `ANSI_MODE`, `TIMEZONE`, + * query-tag presets, …). Forwarded verbatim to SEA + * `session_confs`. Unknown keys are rejected server-side. */ - fetchNextBatch(): Promise + sessionConf?: Record /** - * Result schema as an Arrow IPC payload (schema header only, no - * record-batch message). Available before any batches have been - * fetched, and remains available after `close()` — the kernel - * materialises the schema eagerly so JS callers can build error - * reports against a disposed statement. - * - * Sync because the body has no `.await` — `encode_ipc_stream` is - * pure CPU work over an `Arc` already cached on the - * wrapper. Mirrors `pyo3/src/statement.rs::arrow_schema` (sync). - * napi-rs converts a panic in a sync `#[napi]` entry point into a - * thrown JS error via its own macro-expanded boundary, so the - * `util::guarded` `catch_unwind` wrapper that the `async fn` - * entry points use is not required for this method. + * Select whether `GEOMETRY` / `GEOGRAPHY` results use their native Arrow + * representation. `true` (the default) requests Arrow + * `struct` values; `false` requests WKT / EWKT + * in Arrow UTF-8 values. The kernel normalizes both standard-warehouse + * text and Reyden native Arrow results locally and never sends this choice + * to SEA. */ - schema(): ArrowSchema + enableGeoSpatialSupport?: boolean /** - * Server-side cancel. - * - * For executed statements: short-circuits to `Ok(())` if - * `fetchNextBatch` has already returned `null` (stream - * naturally exhausted) — matches the JDBC `Statement.cancel()` - * no-op-after-completion contract, so JS callers can fire cancel - * defensively without distinguishing "real cancel" from "raced - * with natural completion." - * - * For metadata streams: no-op (the kernel has no in-flight - * cancellation surface for metadata calls today). - * - * Returns `KernelError(InvalidStatementHandle)` if the statement - * has been explicitly `close()`d. + * Driver name reported in telemetry system configuration. Omitted ⇒ + * kernel default. */ - cancel(): Promise + driverName?: string /** - * Explicit close. - * - * For executed statements: awaits the server-side `CloseStatement` - * so the JS caller can observe failures (auth revoked mid-session, - * network error, server-side error). Idempotent — a second call - * on an already-closed statement returns `Ok`. - * - * **Errors are terminal from the JS side.** The kernel executed - * handle is taken out of `inner` BEFORE the wire `CloseStatement` - * runs (so `Drop` knows there's nothing left to clean up). On - * `Err`, the napi `inner` is already `None`, so a JS-side retry - * sees a closed statement and returns `Ok(())` without re- - * attempting the wire call. The kernel-level `ExecutedStatement` - * has been consumed at that point and the value is dropped on - * the way out of the closure — the kernel's `ExecutedStatement:: - * Drop` then fires-and-forgets a single retry on the captured - * runtime. The JS caller can log the error but cannot drive a - * further retry. If you need retry-on-failure semantics for - * `CloseStatement`, layer them above this method. - * - * For metadata streams: drops the stream (no server round-trip - * needed — metadata results have no in-flight server-side - * resource to release). + * Driver version reported in telemetry system configuration. Omitted ⇒ + * kernel default. */ - close(): Promise -} - -/** - * A single Arrow IPC stream payload encoding one record batch (plus - * the schema header so the JS-side reader is stateless). - */ -export interface ArrowBatch { + driverVersion?: string /** - * Arrow IPC stream payload (schema header + 1 record-batch - * message). Decode with `apache-arrow`'s `RecordBatchReader`. + * Runtime name reported in telemetry system configuration. Omitted ⇒ + * kernel default. */ - ipcBytes: Buffer -} - -/** - * An Arrow IPC stream payload encoding just the result schema (no - * record-batch messages). Returned by `Statement.schema()`. - */ -export interface ArrowSchema { + runtimeName?: string /** - * Arrow IPC stream payload (schema header only, no record-batch - * messages). Decode with `apache-arrow`'s `RecordBatchReader` — - * the reader will expose the schema and immediately end. + * Runtime version reported in telemetry system configuration. Omitted ⇒ + * kernel default. */ - ipcBytes: Buffer -} - -/** - * Authentication mode selector crossing the napi boundary. The string - * literals are what napi-rs emits from this `#[napi(string_enum)]` — the - * NodeJS SEA adapter (`KernelAuth`) matches them verbatim (`'Pat'`, - * `'OAuthM2m'`, `'OAuthU2m'`, `'AzureSpM2m'`). - * - * Mirrors the kernel [`AuthConfig`] variants this binding supports. - * `OAuthFederation` / `External` are intentionally not exposed yet — the - * kernel marks federation as not-yet-implemented and `External` is a - * Rust-trait escape hatch with no JS-callback bridge. - */ -export declare const enum AuthMode { - /** Personal access token (`token`). */ - Pat = 'Pat', - /** OAuth 2.0 machine-to-machine — `oauthClientId` + `oauthClientSecret`. */ - OAuthM2m = 'OAuthM2m', + runtimeVersion?: string /** - * OAuth 2.0 machine-to-machine with a JWT private-key client - * assertion — `oauthClientId` + `jwtKeyFile` + `jwtKid`. + * Runtime vendor reported in telemetry system configuration. Omitted ⇒ + * kernel default. */ - OAuthM2mJwt = 'OAuthM2mJwt', + runtimeVendor?: string /** - * OAuth 2.0 user-to-machine (browser flow) — optional `oauthClientId` - * + `oauthRedirectPort`. + * Operating system name reported in telemetry system configuration. + * Omitted ⇒ kernel default. */ - OAuthU2m = 'OAuthU2m', - /** - * Azure Entra service-principal M2M — `azureClientId` + - * `azureClientSecret` (+ optional `azureTenantId` / - * `azureWorkspaceResourceId`). The kernel builds the Entra token - * endpoint + `.default` scope, auto-discovers the tenant from the - * workspace when `azureTenantId` is omitted, and — when - * `azureWorkspaceResourceId` is set — additionally sends the SP - * management token for an RBAC-only service principal. - */ - AzureSpM2m = 'AzureSpM2m' -} - -/** - * JS-visible options for opening a Databricks SQL session. - * - * Authentication is selected by `authMode` (default [`AuthMode::Pat`]): - * - `Pat` — `token` required. - * - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required. - * - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional - * (defaults to the `databricks-sql-connector` client on port 8030). - * - `AzureSpM2m` — `azureClientId` + `azureClientSecret` required - * (+ optional `azureTenantId` / `azureWorkspaceResourceId`). - * - * Catalog / schema / sessionConf are applied once at session creation - * and remain in effect for every statement run on the resulting - * `Connection`. The SEA wire protocol carries them on - * `CreateSession`, not on `ExecuteStatement` — so there is no - * per-statement override path on this binding. - */ -export interface ConnectionOptions { - /** - * Workspace host, e.g. `adb-…azuredatabricks.net`. The kernel - * normalises this — bare hostnames get `https://` prepended. - */ - hostName: string - /** - * JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The - * kernel parses out the warehouse id. - */ - httpPath: string - /** - * Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat: - * existing PAT callers pass only `token`). - */ - authMode?: AuthMode - /** - * Personal access token. Required (and non-empty) for - * [`AuthMode::Pat`]; ignored otherwise. - */ - token?: string - /** - * OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for - * [`AuthMode::OAuthU2m`] (defaults to `databricks-sql-connector`). - */ - oauthClientId?: string - /** OAuth client secret. Required for [`AuthMode::OAuthM2m`]. */ - oauthClientSecret?: string - /** - * Localhost callback port for the [`AuthMode::OAuthU2m`] browser - * flow. Omitted ⇒ kernel default (8030). - */ - oauthRedirectPort?: number - /** - * OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults - * (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M). - */ - oauthScopes?: Array - /** - * OAuth token endpoint override. When omitted the kernel discovers the - * endpoint via the workspace's OIDC configuration. Set it to point the - * client-credentials / JWT client-assertion grant at the workspace's - * configured IdP token endpoint (e.g. Entra ID for Azure Databricks), - * which is required when that IdP — not Databricks-native OIDC — is the - * authority for [`AuthMode::OAuthM2m`] / [`AuthMode::OAuthM2mJwt`]. - */ - tokenUrl?: string - /** - * U2M on-disk token-cache control (kernel path). Omitted ⇒ the kernel - * default (cache enabled, encrypted under a machine-local key, survives - * restarts). `false` disables on-disk persistence (re-login each fresh - * process); `true` keeps it enabled. Applies to [`AuthMode::OAuthU2m`]. - */ - tokenCacheEnabled?: boolean - /** - * Optional passphrase for the U2M on-disk token cache (AES-256 key). - * Omitted/blank ⇒ a machine-local derived key. Supplying one is stronger. - * A passphrase with no explicit `tokenCacheEnabled` implies enabled. - * Applies to [`AuthMode::OAuthU2m`]. - */ - tokenCachePassphrase?: string - /** - * Path to the PEM private-key file. Required for - * [`AuthMode::OAuthM2mJwt`]. - */ - jwtKeyFile?: string - /** JWT key id (`kid`). Required for [`AuthMode::OAuthM2mJwt`]. */ - jwtKid?: string - /** - * Passphrase for an encrypted PKCS#8 key. Optional for - * [`AuthMode::OAuthM2mJwt`] (omit for an unencrypted key). - */ - jwtPassphrase?: string - /** - * JWT signing algorithm (`RS256`/`384`/`512`, `PS256`/`384`/`512`, - * `ES256`, `ES384`). Optional for [`AuthMode::OAuthM2mJwt`] - * (omitted ⇒ kernel default `RS256`). - */ - jwtAlgorithm?: string - /** - * SP-wide Workload Identity Federation client id used during mandatory - * token exchange. Omitted selects BYOT / account-wide WIF. - */ - identityFederationClientId?: string - /** - * Azure Entra app-registration client id. Required for - * [`AuthMode::AzureSpM2m`]; ignored otherwise. - */ - azureClientId?: string - /** - * Azure Entra app-registration client secret. Required for - * [`AuthMode::AzureSpM2m`]. - */ - azureClientSecret?: string - /** - * Azure Entra tenant id. Optional for [`AuthMode::AzureSpM2m`]; - * omitted ⇒ the kernel auto-discovers it from the workspace's - * `/aad/auth` redirect (matching the Thrift connector). - */ - azureTenantId?: string - /** - * Azure workspace ARM resource id. Optional for [`AuthMode::AzureSpM2m`]; - * when set the kernel also sends the SP management token - * (`X-Databricks-Azure-SP-Management-Token`) + the - * `X-Databricks-Azure-Workspace-Resource-Id` header, so a service - * principal with an Azure RBAC role but no workspace membership can - * authenticate. Omitted ⇒ the data token authenticates alone. - */ - azureWorkspaceResourceId?: string - /** - * Default catalog for statements executed on this session. - * Routed through the kernel's `DefaultOpts` and onto the SEA - * `CreateSession.catalog` wire field. - */ - catalog?: string - /** - * Default schema for statements executed on this session. - * Routed through the kernel's `DefaultOpts` and onto the SEA - * `CreateSession.schema` wire field. - */ - schema?: string - /** - * Server-bound session conf (Spark conf, `ANSI_MODE`, `TIMEZONE`, - * query-tag presets, …). Forwarded verbatim to SEA - * `session_confs`. Unknown keys are rejected server-side. - */ - sessionConf?: Record - /** - * Select whether `GEOMETRY` / `GEOGRAPHY` results use their native Arrow - * representation. `true` (the default) requests Arrow - * `struct` values; `false` requests WKT / EWKT - * in Arrow UTF-8 values. The kernel normalizes both standard-warehouse - * text and Reyden native Arrow results locally and never sends this choice - * to SEA. - */ - enableGeoSpatialSupport?: boolean - /** - * Driver name reported in telemetry system configuration. Omitted ⇒ - * kernel default. - */ - driverName?: string - /** - * Driver version reported in telemetry system configuration. Omitted ⇒ - * kernel default. - */ - driverVersion?: string - /** - * Runtime name reported in telemetry system configuration. Omitted ⇒ - * kernel default. - */ - runtimeName?: string - /** - * Runtime version reported in telemetry system configuration. Omitted ⇒ - * kernel default. - */ - runtimeVersion?: string - /** - * Runtime vendor reported in telemetry system configuration. Omitted ⇒ - * kernel default. - */ - runtimeVendor?: string - /** - * Operating system name reported in telemetry system configuration. - * Omitted ⇒ kernel default. - */ - osName?: string + osName?: string /** * Operating system version reported in telemetry system configuration. * Omitted ⇒ kernel default. @@ -958,7 +514,9 @@ export interface ConnectionOptions { * `User-Agent` entry here. */ customHeaders?: Array - /** Whether SEA API responses may use HTTP compression. Defaults to false. */ + /** + * Whether SEA API responses may use HTTP compression. Defaults to false. + */ seaResponseCompressionEnabled?: boolean /** * Retry/backoff tuning — all optional. An unset field keeps the kernel's @@ -989,13 +547,10 @@ export interface ConnectionOptions { */ retryOverallTimeoutSecs?: number /** - * Enable kernel telemetry export. Tri-state: an explicit `true` or `false` - * takes precedence; when omitted, export defers to the - * `enableTelemetryForKernel` workspace feature flag, falling back to - * disabled when the flag is absent. Only an explicit `false` guarantees - * telemetry stays disabled. When enabled, the kernel records operation - * telemetry below the binding layer and exports through the Databricks SQL - * driver telemetry endpoint. + * Enable kernel telemetry export. Omitted / `false` keeps telemetry + * disabled. When enabled, the kernel records operation telemetry below the + * binding layer and exports through the Databricks SQL driver telemetry + * endpoint. */ telemetryEnabled?: boolean /** @@ -1021,9 +576,9 @@ export interface ConnectionOptions { /** Enable telemetry circuit-breaker protection. Omitted ⇒ kernel default. */ telemetryCircuitBreakerEnabled?: boolean /** - * Consecutive telemetry export failures before opening the circuit. - * Omitted ⇒ kernel default. Must be greater than zero when the circuit - * breaker is enabled. + * Consecutive telemetry export failures before opening the circuit. Omitted + * ⇒ kernel default. Must be greater than zero when the circuit breaker is + * enabled. */ telemetryCircuitBreakerThreshold?: number /** @@ -1060,134 +615,41 @@ export interface ConnectionOptions { */ socketTimeoutMs?: number } - /** - * Per-statement options for `Connection.executeStatement`. + * Open a Databricks SQL session and return an opaque `Connection` + * wrapping the kernel `Session`. Authentication is selected by + * `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see + * [`build_auth_config`]. * - * Mirrors the kernel `StatementSpec` knobs that are safe to thread - * through napi without a kernel-side change. Today this covers: - * - `statementConf` — per-statement Spark conf overlay - * (`StatementSpec.statement_conf` → SEA `parameters` / - * Thrift `confOverlay`) - * - `queryTags` — convenience wrapper over `statementConf` with - * key `query_tags`; serialised to the same comma-separated - * `key:value` wire shape NodeJS Thrift's `serializeQueryTags` - * produces (`lib/utils/queryTags.ts`). Backslashes in keys are - * doubled; backslash/colon/comma in values are backslash-escaped. + * The JS-visible name is `openSession` (napi-rs converts snake_case + * to camelCase for free functions). + */ +export declare function openSession(options: ConnectionOptions): Promise +/** + * One kernel log event, as handed to JS. `level` is a lower-case string + * (`error`/`warn`/`info`/`debug`/`trace`) the Node side maps onto its + * `LogLevel`; `target` is the originating `tracing` target (e.g. + * `databricks::sql::kernel`); `message` is the rendered event plus any + * structured `key=value` fields. + */ +export interface LogRecord { + level: string + target: string + message: string +} +/** + * Install (idempotently) the kernel→JS log bridge and set its level. * - * `rowLimit` (SEA `row_limit`) is exposed here and threaded onto the kernel - * `StatementSpec`. `positionalParams` (`?`) and `namedParams` (`:name`) - * carry bound query parameters, decoded via `params::parse_typed_value`. - * `rawParams` forwards pre-marshalled SEA parameters unchanged. - * (There is no `queryTimeoutSecs`: it abused the SEA `wait_timeout` inline-hold - * window and was removed — a real per-statement timeout is `STATEMENT_TIMEOUT`.) + * `callback` is invoked with **an array of [`LogRecord`]s** (`(err, records)`) + * for each forwarded batch. `level` is one of + * `off`/`error`/`warn`/`info`/`debug`/`trace` (case-insensitive); unknown + * values fall back to `warn`. * - * **Tag-order caveat (M4 parity note).** The napi `queryTags` field - * is a Rust `HashMap` whose iteration order is - * non-deterministic, so the serialised `query_tags` value may have - * a different key order than Thrift's `serializeQueryTags` (which - * iterates `Object.keys(...)` in insertion order) for the same - * input. The SEA server is order-insensitive on conf values, so - * the two are functionally equivalent. If a caller needs - * byte-identical Thrift parity, the JS adapter pre-serialises via - * `serializeQueryTags` and writes the result into - * `statementConf["query_tags"]` directly — see - * `KernelSessionBackend.executeStatement` in the NodeJS driver. This - * path is the one the production code uses. + * Safe to call more than once: the process-global subscriber is installed on + * the first call only, while every call refreshes the sink + level (last + * writer wins — see module docs). */ -export interface ExecuteOptions { - /** - * Per-statement Spark conf overlay. Merged on top of the - * session-level `sessionConf` at execute time; this map wins - * on key collisions. Unknown keys are rejected by the server. - */ - statementConf?: Record - /** - * Query tags as key→value pairs. Serialised to a comma- - * separated `key:value` string (backslash-escaping `\`, `:`, - * `,`) and placed into `statementConf["query_tags"]`, matching - * NodeJS Thrift's `serializeQueryTags` wire shape. Passing - * both `queryTags` AND a `query_tags` key in `statementConf` - * raises `InvalidArgument` — the caller's intent is ambiguous - * so we refuse to silently pick one over the other. - * - * A **`null`** value emits a **bare key** (no colon) — e.g. - * `{ production: null }` → `"production"` — matching the - * connectors' `key`-only tag form. - * - * See the struct-level "Tag-order caveat" for the - * HashMap-iteration-order vs `Object.keys`-iteration-order - * divergence and the byte-identical-Thrift-parity workaround. - */ - queryTags?: Record - /** - * Server-side cap on the number of rows this statement returns - * (SEA `row_limit`), independent of any SQL `LIMIT`. Maps to - * `StatementSpec.row_limit`. Omitted ⇒ no driver-imposed cap. - */ - rowLimit?: number - /** - * Positional parameters, in 1-based wire order. Index `i` in this - * Vec corresponds to the `i+1`-th `?` placeholder in the SQL. - * Each entry is a `{ sqlType, value }` pair — `value` is the - * string-encoded literal or `null` for SQL NULL. Mirrors - * `StatementSpec::positional_params`; decoded via [`parse_typed_value`]. - */ - positionalParams?: Array - /** - * Named parameters (`:name` placeholders). Each carries its `name` - * alongside the `{ sqlType, value? }` pair. Mapped to a kernel - * `TypedValue` via the same [`parse_typed_value`] codec and bound with - * `StatementSpec::param_named`. Named is the SEA-spec-required public - * param form (`StatementParameter.name` is `openapi_required`); - * positional is the documented-undocumented variant. The two are - * mutually exclusive at the SQL level (`?` vs `:name`). - */ - namedParams?: Array - /** - * Pre-marshalled parameters passed through `StatementSpec::param_raw`. - * Omit `name` for positional values. Raw parameters cannot be mixed with - * typed parameters or combine named and positional markers. - */ - rawParams?: Array -} - -/** - * A single extra HTTP header as an explicit `{ name, value }` pair. - * - * An ordered list of these (`ConnectionOptions.custom_headers`) mirrors - * the kernel core's `Vec<(String, String)>` and the pyo3 binding's - * `http_headers`: order is preserved and duplicate `name`s are allowed. - * A struct (rather than a raw `[name, value]` tuple) because napi-rs - * does not marshal Rust tuples through `#[napi(object)]` fields; the - * struct is the idiomatic, self-documenting equivalent and maps to a JS - * `{ name: string, value: string }`. - */ -export interface HeaderEntry { - name: string - value: string -} - -/** - * Install (idempotently) the kernel→JS log bridge and set its level. - * - * `callback` is invoked with **an array of [`LogRecord`]s** (`(err, records)`) - * for each forwarded batch. `level` is one of - * `off`/`error`/`warn`/`info`/`debug`/`trace` (case-insensitive); unknown - * values fall back to `warn`. - * - * Safe to call more than once: the process-global subscriber is installed on - * the first call only, while every call refreshes the sink + level (last - * writer wins — see module docs). - */ -export declare function initKernelLogging(callback: ((err: Error | null, arg: Array) => any), level: string): void - -/** - * Return the bridge's [`KernelLoggingStats`]. Safe to call before - * `initKernelLogging` (reports `installed: false`, `dropped: 0`). - */ -export declare function kernelLoggingStats(): KernelLoggingStats - +export declare function initKernelLogging(callback: (err: Error | null, arg: Array) => any, level: string): void /** * Snapshot of the bridge's runtime state for observability. * @@ -1203,81 +665,16 @@ export interface KernelLoggingStats { installed: boolean dropped: number } - -/** - * One kernel log event, as handed to JS. `level` is a lower-case string - * (`error`/`warn`/`info`/`debug`/`trace`) the Node side maps onto its - * `LogLevel`; `target` is the originating `tracing` target (e.g. - * `databricks::sql::kernel`); `message` is the rendered event plus any - * structured `key=value` fields. - */ -export interface LogRecord { - level: string - target: string - message: string -} - -/** - * A named bound parameter — a [`TypedValueInput`] plus its `:name`. Kept a - * distinct napi object (rather than an optional `name` on `TypedValueInput`) - * so the positional surface stays a clean ordered list with no name field. - */ -export interface NamedTypedValueInput { - name: string - sqlType: string - value?: string -} - -/** - * Open a Databricks SQL session and return an opaque `Connection` - * wrapping the kernel `Session`. Authentication is selected by - * `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see - * [`build_auth_config`]. - * - * The JS-visible name is `openSession` (napi-rs converts snake_case - * to camelCase for free functions). - */ -export declare function openSession(options: ConnectionOptions): Promise - -/** - * Programmatic HTTP/HTTPS proxy configuration, mirroring the kernel's - * internal [`ProxyConfig`]. Supplied as a structured object rather than a - * flattened URL so credentials never have to be percent-encoded into the URL - * and the bypass-host list can be expressed. - * - * - `url` — proxy endpoint, e.g. `"http://proxy.corp.example.com:8080"`. Must - * use the `http://` or `https://` scheme. - * - `username` / `password` — optional proxy basic-auth, applied via - * `reqwest`'s `Proxy::basic_auth` (not embedded in the URL). - * - `bypassHosts` — optional comma-separated host/domain list that should - * bypass the proxy (e.g. `"localhost,*.internal.corp"`). - */ -export interface ProxyInput { - url: string - username?: string - password?: string - bypassHosts?: string -} - /** - * A pre-marshalled SEA parameter that preserves `sql_type` verbatim. - * Omit `name` for positional markers; the kernel assigns their ordinals. + * Return the bridge's [`KernelLoggingStats`]. Safe to call before + * `initKernelLogging` (reports `installed: false`, `dropped: 0`). */ -export interface RawParameterInput { - /** Named marker name. Omit for a positional marker. */ - name?: string - /** Databricks SQL type name sent verbatim to SEA. */ - sqlType: string - /** String-encoded value. `None` represents SQL NULL. */ - value?: string -} - +export declare function kernelLoggingStats(): KernelLoggingStats /** * Live-retarget the bridge's level (one of * `off`/`error`/`warn`/`info`/`debug`/`trace`, case-insensitive). */ export declare function setKernelLogLevel(level: string): void - /** * JS-visible binding for a single positional parameter. * @@ -1311,7 +708,41 @@ export interface TypedValueInput { */ value?: string } - +/** + * A pre-marshalled SEA parameter that preserves `sql_type` verbatim. + * Omit `name` for positional markers; the kernel assigns their ordinals. + */ +export interface RawParameterInput { + /** Named marker name. Omit for a positional marker. */ + name?: string + /** Databricks SQL type name sent verbatim to SEA. */ + sqlType: string + /** String-encoded value. `None` represents SQL NULL. */ + value?: string +} +/** + * A single Arrow IPC stream payload encoding one record batch (plus + * the schema header so the JS-side reader is stateless). + */ +export interface ArrowBatch { + /** + * Arrow IPC stream payload (schema header + 1 record-batch + * message). Decode with `apache-arrow`'s `RecordBatchReader`. + */ + ipcBytes: Buffer +} +/** + * An Arrow IPC stream payload encoding just the result schema (no + * record-batch messages). Returned by `Statement.schema()`. + */ +export interface ArrowSchema { + /** + * Arrow IPC stream payload (schema header only, no record-batch + * messages). Decode with `apache-arrow`'s `RecordBatchReader` — + * the reader will expose the schema and immediately end. + */ + ipcBytes: Buffer +} /** * Returns the native binding's crate version (`CARGO_PKG_VERSION`). * @@ -1319,3 +750,541 @@ export interface TypedValueInput { * loaded?" probe for the JS-side loader's structured diagnostics. */ export declare function version(): string +/** + * Opaque async-statement handle. + * + * Returned by `Connection.submitStatement(...)` after the kernel + * `Statement::submit()` returns (server sent `wait_timeout=0s`, so + * the response carries a `statement_id` but the statement is still + * `Pending`/`Running`). JS drives polling via `status()` / + * `awaitResult()`. + * + * Concurrency shape: `status()`, `awaitResult()`, and `close()` take + * `inner.lock()` and hold the guard across the kernel `.await` (tokio + * `Mutex` is FIFO), so `status()` / `close()` queue behind any + * in-flight `awaitResult()` until it returns naturally. `cancel()` is + * the deliberate exception: it does **not** touch `inner` — it fires + * through the detached `AsyncStatementCanceller` (session + + * statement_id, captured at construction), so an explicit + * `stmt.cancel()` interrupts an in-flight `awaitResult()` instead of + * queueing behind it. The server-side cancel flips the statement + * terminal, which the parked `awaitResult()` poll loop observes + * (`Cancelled`) and returns on. The kernel's `AwaitResultCancelGuard` + * still covers the drop-cancel case (Promise.race / timeout) + * independently — see module docs. + */ +export declare class AsyncStatement { + /** + * Server-issued statement id. Cached at construction; readable + * even after `close()` so JS-side log lines can correlate + * against kernel / server logs which key on the same id. + */ + get statementId(): string + /** + * One-shot status check. Returns a string enum matching the + * kernel `StatementStatus` shape: + * `'Pending' | 'Running' | 'Succeeded' | 'Failed' | + * 'Cancelled' | 'Closed' | 'Unknown'`. (`'Unknown'` is the + * `#[non_exhaustive]` forward-compat catch-all that + * `StatementStatus::as_str` can return — consumers switching on + * the state must handle it.) Returns + * `KernelError(InvalidStatementHandle)` if the statement has + * been explicitly `close()`d. + * + * The `Failed` variant collapses to the string `'Failed'` on + * the JS side; the underlying error envelope (sql_state / + * error_code / query_id) is surfaced by `awaitResult()`'s + * rejection, which is where callers actually need the typed + * error. `status()` is intended for polling progress UIs + * that only need the state name. + */ + status(): Promise + /** Rows modified by the statement (UPDATE / INSERT / DELETE / MERGE). */ + numModifiedRows(): Promise + /** + * Server-supplied user-facing message (may contain SQL fragments — + * redact before centralised logging). + */ + displayMessage(): Promise + /** Server-supplied diagnostic detail. */ + diagnosticInfo(): Promise + /** Server-supplied structured error detail (JSON), when enabled. */ + errorDetailsJson(): Promise + /** + * Block until the server reaches a terminal state, then return + * an `AsyncResultHandle` that wraps the materialised result + * stream. The handle exposes `fetchNextBatch()` / `schema()` + * for consuming the result, plus `statementId` for log + * correlation. + * + * Drop-cancel safety: kernel `await_result` installs + * `AwaitResultCancelGuard` which fires a fire-and-forget + * `cancel_statement` if the future is dropped mid-poll + * (timeout, tokio::select! loser, JS-side `Promise.race` + * loser). The `util::guarded` `catch_unwind` here covers the + * V8-panic-across-boundary case on top. Returns + * `KernelError(InvalidStatementHandle)` if the statement has + * been explicitly `close()`d. + */ + awaitResult(): Promise + /** + * Server-side cancel. Returns + * `KernelError(InvalidStatementHandle)` if the statement has + * been explicitly `close()`d. Idempotent against a server + * that already reached a terminal state — the kernel's + * `cancel_statement` is a no-op there. + * + * **Lock-free by design.** Unlike `status()` / `awaitResult()` / + * `close()`, this does not take `inner.lock()` — it fires through + * the detached `AsyncStatementCanceller` captured at construction. + * That lets `stmt.cancel()` interrupt an in-flight `awaitResult()` + * (which holds the mutex for the whole poll) instead of queueing + * behind it: the server-side cancel flips the statement terminal, + * the parked `awaitResult()` poll loop observes `Cancelled` and + * returns. The closed-state check reads a lock-free flag so a + * cancel after an explicit `close()` still surfaces + * `InvalidStatementHandle`. + */ + cancel(): Promise + /** + * Explicit close. Idempotent — a second call on an + * already-closed handle returns `Ok(())`. On `Err`, the napi + * inner is already `None`, so a JS-side retry sees the + * closed-handle short-circuit and returns `Ok(())` without + * re-attempting the wire call. The kernel's own `Drop` + * fire-and-forget retry runs once in the background. + */ + close(): Promise +} +/** + * Opaque result-fetch handle returned by + * `AsyncStatement.awaitResult()`. Wraps a kernel `ResultStream` + * directly; structurally analogous to the sync `Statement`'s + * fetch-side surface (`fetchNextBatch` / `schema` / + * `statementId`). + * + * `cancel()` / `close()` are not exposed: the parent + * `AsyncStatement` owns server-side lifecycle. A `close()` here + * would create dual-ownership of the same statement_id with + * inconsistent close semantics. Callers `close()` the parent + * `AsyncStatement` after they're done fetching. + * + * Schema is cached at construction so it survives the underlying + * stream being drained; mirrors the sync `Statement.schema()` + * post-close contract. + */ +export declare class AsyncResultHandle { + /** + * Server-issued statement id. Cached at construction; readable + * for log correlation. Matches the parent `AsyncStatement`'s + * `statementId`. + */ + get statementId(): string + /** + * Pull the next batch of results. Returns `null` when the + * stream is exhausted. The returned `ArrowBatch.ipcBytes` is a + * complete Arrow IPC stream (schema header + 1 record-batch + * message), suitable for handing to `apache-arrow`'s + * `RecordBatchReader`. Byte-identical to the sync + * `Statement.fetchNextBatch()` payload for the same query. + */ + fetchNextBatch(): Promise + /** + * Result schema as an Arrow IPC payload (schema header only, + * no record-batch message). Available before any batches have + * been fetched. Sync because the body has no `.await` — + * `encode_ipc_stream` is pure CPU work over the cached + * `Arc`. + */ + schema(): ArrowSchema +} +/** + * Handle returned by `Connection.executeStatementCancellable`. Owns the + * built-but-not-yet-executed kernel `Statement` plus a detached + * [`StatementCanceller`] captured before dispatch, so JS can fire a + * server-side cancel while the blocking `result()` is in flight. + * + * `pending` is `Arc>>` so `result()` can + * `.take()` the statement (the kernel `execute()` borrows it `&mut`, + * then it moves into the produced `Statement` wrapper to keep its + * `ValidityFlag` set — see `statement.rs`). A second `result()` call + * after the first resolved surfaces `InvalidStatementHandle`. + */ +export declare class CancellableExecution { + /** + * The server-issued statement id this execution targets, if the + * server has issued one yet (`null` before the initial submit + * round-trip publishes it mid-`result()`). Useful for log + * correlation while the blocking drive is in flight. + */ + get statementId(): string | null + /** + * Drive the blocking `execute()` and resolve to a `Statement` + * (identical to what `executeStatement` returns) once the kernel + * reaches a terminal state and the result stream is ready. + * + * Consumes the pending statement: a second `result()` call returns + * `KernelError(InvalidStatementHandle)`. The future is + * drop-cancel-safe — the kernel's per-execute `MidExecuteCancelState` + * guard fires a fire-and-forget `cancel_statement` if this future is + * dropped mid-flight (`Promise.race` / timeout loser), independently + * of an explicit `cancel()`. + * + * On a server-side cancel the kernel's blocking `execute()` currently + * surfaces `InvalidArgument` (a known kernel quirk — the async path + * returns `Cancelled`). When this handle's `cancel()` actually dispatched a + * server-side cancel, we normalise that into `Cancelled` here so JS callers + * can rely on a single cancelled-status code regardless of execution path. + * + * Three outcomes can race the blocking drive: (1) a natural terminal state + * → `Ok` or the genuine error; (2) an explicit `cancel()` that dispatched a + * server cancel → this `result()` rejects with a `Cancelled`-coded error + * (the normalisation above); (3) the future being **dropped** mid-flight + * (`Promise.race`/timeout loser) → the kernel's `MidExecuteCancelState` + * drop-guard fires a fire-and-forget `cancel_statement`, but there is no + * `result()` left to observe a code. Only (2) yields a `Cancelled` error. + */ + result(): Promise + /** + * Server-side cancel of the in-flight statement. + * + * Lock-free: fires the detached `StatementCanceller` captured at + * construction rather than taking the mutex `result()` holds, so it + * interrupts a still-running blocking `result()` instead of queueing + * behind it. No-op (returns `Ok`) if `result()` already finished + * successfully, or if no statement id has been observed yet (query still + * in its initial submit round-trip), and idempotent against a server + * already in a terminal state. + */ + cancel(): Promise +} +/** + * Opaque connection handle wrapping a kernel `Session`. + * + * `inner` is `Arc>>` so: + * - the Drop impl can clone the `Arc` and `.take()` the session on a + * background tokio task without holding `&mut self` (which Drop is + * forbidden from doing across an `await`), + * - `close()` can `.take()` the session to consume it for the kernel's + * move-by-value `Session::close(self)` signature. + * + * **Concurrency shape** — both `executeStatement` and + * `submitStatement` build the kernel `Statement` under `inner.lock()` + * and then RELEASE the guard before the wire call + * (`stmt.execute().await` / `stmt.submit().await`). `Session::statement()` + * is `&self`-callable and only clones the session's internal `Arc`, so + * the built statement is independent of the guard. Concurrent + * `Promise.all([executeStatement(q1), submitStatement(q2)])` therefore + * serialise only for the microsecond statement-build, not the network + * round-trip, and `close()` never blocks behind an in-flight execute or + * submit. See + * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. + */ +export declare class Connection { + /** + * Server-issued session id. Cached at construction; readable + * even after `close()` so JS-side log lines can correlate + * against kernel / server logs which key on the same id. + */ + get sessionId(): string + /** + * Execute a SQL statement and return a Statement handle that + * streams batches via `fetchNextBatch()`. + * + * Catalog / schema / sessionConf are session-level + * (`openSession`). Per-statement options on `ExecuteOptions`: + * - `statementConf` — per-statement Spark conf overlay + * - `queryTags` — serialised to a comma-separated `key:value` + * string and placed in `statement_conf["query_tags"]`, + * matching NodeJS Thrift's `serializeQueryTags` wire shape + * + * `options` is omitted/`None` for the no-options path; passing + * `{ statementConf: {} }` (an empty map) is treated the same as + * omission to keep the wire shape stable for the common case. + */ + executeStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise + /** + * directResults execute — the Thrift/JDBC model. Sends ExecuteStatement + * with no `wait_timeout` field (server applies its ~10s default inline wait + * and auto-closes on success) and returns WITHOUT polling past it: + * + * - a **`Statement`** (left arm) when the query finished within the inline + * wait — terminal, result ready inline, `close()` is a clean release; + * - an **`AsyncStatement`** (right arm) when it did not — a poll/cancel + * handle the caller drives (`status()` / `awaitResult()` / `cancel()`). + * + * JS distinguishes the arms by feature-detecting `awaitResult` (present + * only on `AsyncStatement`). This is the path that gives mid-run cancel for + * long queries WITHOUT the eager-handle / close-drives workaround: the + * returned handle always corresponds to a server-owned statement. + * + * **Load-bearing contract:** the kernel's `DirectStatement::{Completed, + * Running}` discriminant cannot ride on these opaque `#[napi]` classes, so + * consumers MUST feature-detect via `awaitResult` (the only member unique to + * `AsyncStatement`). `Statement` (the Completed arm) MUST NOT gain an + * `awaitResult` member, or every consumer silently misroutes. The pyo3 + * binding makes the same `await_result`-probe assumption. + */ + executeStatementDirect(sql: string, options?: ExecuteOptions | undefined | null): Promise + /** + * Execute a SQL statement on the blocking (sync) path, but return a + * `CancellableExecution` handle so a concurrent JS task can cancel + * the query *while it is still running server-side*. + * + * `executeStatement` builds the kernel `Statement`, awaits the + * blocking `execute()`, and only then hands JS a `Statement` — so a + * query that runs for several seconds is uncancellable from JS on + * that path (there is no handle until the blocking call resolves). + * This method instead builds the statement, captures a detached + * `StatementCanceller` **before** dispatching `execute()`, and hands + * JS a `CancellableExecution` immediately. The caller drives the + * blocking execution via `result()` (resolves to the same + * `Statement` `executeStatement` returns) and can fire `cancel()` + * concurrently to interrupt a still-running query mid-COMPUTE. + * + * Option semantics are identical to `executeStatement`. + * Mirrors the pyo3 `Statement.canceller()` / `Statement.execute()` + * split (PR #121): obtain the canceller before the blocking drive. + */ + executeStatementCancellable(sql: string, options?: ExecuteOptions | undefined | null): Promise + /** + * Submit a SQL statement and return immediately with an + * `AsyncStatement` handle, without blocking until the query + * finishes. The kernel's `Statement::submit()` sends + * `wait_timeout=0s`, so the server responds as soon as it has a + * `statement_id` (state `Pending`/`Running`); JS drives polling + * via `AsyncStatement.status()` and materialises results with + * `AsyncStatement.awaitResult()`. + * + * This is the async-execution path the Thrift backend always + * uses (`runAsync: true`): the SEA backend submits, returns a + * pending operation handle, and polls to terminal during + * fetch. Option semantics (statementConf / queryTags / + * rowLimit / positional + named params) match `executeStatement`. + * Submit always sends `wait_timeout=0s` so the call returns + * immediately; the caller drives completion via `status()` / + * `awaitResult()`. Only the blocking-vs-pending return contract + * differs from `executeStatement`. + */ + submitStatement(sql: string, options?: ExecuteOptions | undefined | null): Promise + /** + * Explicit close. Awaits the server-side `DeleteSession` so the + * JS caller can observe failures (auth revoked mid-session, + * warehouse stopped, network error). Idempotent — a second call + * on an already-closed connection returns `Ok`. + * + * **Errors are terminal from the JS side.** The kernel session + * handle is consumed (`take()`) BEFORE the wire `DeleteSession` + * runs, because `Session::close` takes `self` by value. On `Err`, + * the napi `inner` is already `None`, so a JS-side retry sees a + * closed connection and returns `Ok(())` without re-attempting + * the wire call. The kernel's own `Drop` fire-and-forget retry + * runs once in the background — the JS caller can log the error + * but cannot drive a retry. If you need retry-on-failure + * semantics for `DeleteSession`, layer them above this method. + */ + close(): Promise + /** + * All catalogs visible to the session. + * + * JDBC `getCatalogs` shape: `TABLE_CAT: Utf8`. + */ + listCatalogs(): Promise + /** + * Schemas filtered by catalog (exact) and schema name pattern. + * + * JDBC `getSchemas` shape: `TABLE_SCHEM, TABLE_CATALOG`. + */ + listSchemas(catalog?: string | undefined | null, schemaPattern?: string | undefined | null): Promise + /** + * Tables filtered by catalog (exact), schema (pattern), table (pattern). + * + * JDBC `getTables` shape: 10 columns. `tableTypes`, when provided, + * filters rows by `TABLE_TYPE` kernel-side. + * + * `tableTypes` is an advisory filter. Databricks `SHOW TABLES` does + * NOT honour the table-type filter server-side; the kernel applies + * it client-side after the result returns. Callers expecting + * server-side rejection of off-type tables should not rely on this. + */ + listTables(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, tableTypes?: Array | undefined | null): Promise + /** + * Columns of tables matching the filter. + * + * JDBC `getColumns` shape: 23 columns. + */ + listColumns(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, tablePattern?: string | undefined | null, columnPattern?: string | undefined | null): Promise + /** + * Functions visible to the session. `catalog` is exact; + * `schemaPattern` and `functionPattern` are SQL LIKE. + */ + listFunctions(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, functionPattern?: string | undefined | null): Promise + /** + * Procedures visible to the session. `catalog` is exact; + * `schemaPattern` and `procedurePattern` are SQL LIKE. + */ + listProcedures(catalog?: string | undefined | null, schemaPattern?: string | undefined | null, procedurePattern?: string | undefined | null): Promise + /** + * All table types (`TABLE`, `VIEW`, `SYSTEM TABLE`, …). + * No wire call — static in-memory result. + */ + listTableTypes(): Promise + /** + * SQL data types supported by the workspace. + * No wire call — static in-memory result. + */ + listTypeInfo(): Promise + /** + * Primary keys for the given table. All three identifiers are + * exact — ODBC `SQLPrimaryKeys` does not support patterns. + */ + getPrimaryKeys(catalog: string | undefined | null, schema: string | undefined | null, table: string): Promise + /** + * Foreign-key relationships. The parent side is optional. When the + * foreign table is omitted, returns an empty result without issuing a + * server statement. When it is provided, its catalog and schema are + * required. All identifiers are exact — no LIKE patterns. + */ + getCrossReference(parentCatalog: string | undefined | null, parentSchema: string | undefined | null, parentTable: string | undefined | null, foreignCatalog: string | undefined | null, foreignSchema: string | undefined | null, foreignTable: string | undefined | null): Promise +} +/** + * Opaque executed-statement handle. + * + * **Current concurrency shape** — every method takes `inner.lock()` + * and holds the guard across the kernel `.await`. tokio `Mutex` is + * FIFO, so cancel/close queue behind any in-flight `fetchNextBatch` + * until it returns naturally. This is a known limitation that exists + * because the napi shape has not yet been split into an + * `Arc` (for cancel/close, which the + * kernel exposes as `&self`-callable) plus a `Mutex>` only + * for the borrowed-mut fetch path. The lock-shape refactor needs a + * small kernel-side accessor and lands in a follow-up PR — see + * `sea-workflow/jira-candidates/2026-05-24-napi-cancel-during-fetch.md`. + * + * `schema` and `statement_id` are cached at construction so they + * survive `close()` — JS callers building error reports against a + * disposed statement can still read them. + */ +export declare class Statement { + /** + * Server-issued statement id. Cached at construction; readable + * even after `close()` so JS-side log lines can correlate against + * kernel / server logs which key on the same id. + */ + get statementId(): string + /** + * Number of rows modified by the statement (UPDATE / INSERT / + * DELETE / MERGE). `null` for SELECT and on warehouses that don't + * surface the counter. Mirrors Thrift's + * `TGetOperationStatusResp.numModifiedRows`. + */ + numModifiedRows(): Promise + /** + * Server-supplied user-facing message. Mirrors Thrift's + * `TGetOperationStatusResp.displayMessage`. **PII / sensitive- + * data note:** may contain SQL fragments or parameter values — + * redact before centralised logging. + * + * Populated on `Succeeded` / `Closed` paths (incl. an empty `Closed`). + * On terminal-error states (`Failed` / `Cancelled`) the kernel returns + * an Error instead of a `Statement`, and the same field rides on the JS + * Error envelope under the same `displayMessage` key. + */ + displayMessage(): Promise + /** + * Server-supplied diagnostic detail — multi-line operator / + * stack context. Mirrors Thrift's + * `TGetOperationStatusResp.diagnosticInfo`. For support surfaces, + * not user-facing. Same reachability + PII caveats as + * `displayMessage`. + */ + diagnosticInfo(): Promise + /** + * Server-supplied JSON blob with extended error details. Mirrors + * Thrift's `TGetOperationStatusResp.errorDetailsJson`. + * Pass-through string — JS callers parse with `JSON.parse` if + * they need structured access. + * + * **Server-side gating:** populated only when the workspace has + * `spark.databricks.sql.errorDetailsJson.enabled = true` on the + * underlying SQL cluster. The flag is internal-only / default- + * false in the Databricks runtime, so for most JS callers this + * will return `null`. Admin-enabled workspaces return content + * shaped like `{"errorClass": "...", "messageTemplate": "..."}`. + * + * **Unbounded:** when populated, server can return a multi-MB + * blob; size before logging. + */ + errorDetailsJson(): Promise + /** + * Pull the next batch of results. Returns `null` when the stream + * is exhausted. The returned `ArrowBatch.ipcBytes` is a complete + * Arrow IPC stream (schema header + 1 record-batch message) + * suitable for handing to `apache-arrow`'s `RecordBatchReader`. + * + * On `Err`, the stream is in an unspecified state — call + * `close()` and discard the `Statement`. Subsequent + * `fetchNextBatch()` calls after an error are not guaranteed to + * succeed or fail consistently. + */ + fetchNextBatch(): Promise + /** + * Result schema as an Arrow IPC payload (schema header only, no + * record-batch message). Available before any batches have been + * fetched, and remains available after `close()` — the kernel + * materialises the schema eagerly so JS callers can build error + * reports against a disposed statement. + * + * Sync because the body has no `.await` — `encode_ipc_stream` is + * pure CPU work over an `Arc` already cached on the + * wrapper. Mirrors `pyo3/src/statement.rs::arrow_schema` (sync). + * napi-rs converts a panic in a sync `#[napi]` entry point into a + * thrown JS error via its own macro-expanded boundary, so the + * `util::guarded` `catch_unwind` wrapper that the `async fn` + * entry points use is not required for this method. + */ + schema(): ArrowSchema + /** + * Server-side cancel. + * + * For executed statements: short-circuits to `Ok(())` if + * `fetchNextBatch` has already returned `null` (stream + * naturally exhausted) — matches the JDBC `Statement.cancel()` + * no-op-after-completion contract, so JS callers can fire cancel + * defensively without distinguishing "real cancel" from "raced + * with natural completion." + * + * For metadata streams: no-op (the kernel has no in-flight + * cancellation surface for metadata calls today). + * + * Returns `KernelError(InvalidStatementHandle)` if the statement + * has been explicitly `close()`d. + */ + cancel(): Promise + /** + * Explicit close. + * + * For executed statements: awaits the server-side `CloseStatement` + * so the JS caller can observe failures (auth revoked mid-session, + * network error, server-side error). Idempotent — a second call + * on an already-closed statement returns `Ok`. + * + * **Errors are terminal from the JS side.** The kernel executed + * handle is taken out of `inner` BEFORE the wire `CloseStatement` + * runs (so `Drop` knows there's nothing left to clean up). On + * `Err`, the napi `inner` is already `None`, so a JS-side retry + * sees a closed statement and returns `Ok(())` without re- + * attempting the wire call. The kernel-level `ExecutedStatement` + * has been consumed at that point and the value is dropped on + * the way out of the closure — the kernel's `ExecutedStatement:: + * Drop` then fires-and-forgets a single retry on the captured + * runtime. The JS caller can log the error but cannot drive a + * further retry. If you need retry-on-failure semantics for + * `CloseStatement`, layer them above this method. + * + * For metadata streams: drops the stream (no server round-trip + * needed — metadata results have no in-flight server-side + * resource to release). + */ + close(): Promise +} diff --git a/napi/index.js b/napi/index.js index 6902ddee..ad50ecc9 100644 --- a/napi/index.js +++ b/napi/index.js @@ -1,713 +1,325 @@ -// prettier-ignore +/* tslint:disable */ /* eslint-disable */ -// @ts-nocheck +/* prettier-ignore */ + /* auto-generated by NAPI-RS */ -const { readFileSync } = require('fs') -let nativeBinding = null -const loadErrors = [] +const { existsSync, readFileSync } = require('fs') +const { join } = require('path') -const isMusl = () => { - let musl = false - if (process.platform === 'linux') { - musl = isMuslFromFilesystem() - if (musl === null) { - musl = isMuslFromReport() - } - if (musl === null) { - musl = isMuslFromChildProcess() - } - } - return musl -} +const { platform, arch } = process -const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-') - -const isMuslFromFilesystem = () => { - try { - return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl') - } catch { - return null - } -} +let nativeBinding = null +let localFileExisted = false +let loadError = null -const isMuslFromReport = () => { - let report = null - if (process.report && typeof process.report.getReport === 'function') { - process.report.excludeNetwork = true - report = process.report.getReport() - } - if (!report) { - return null - } - if (report.header && report.header.glibcVersionRuntime) { - return false - } - if (Array.isArray(report.sharedObjects)) { - if (report.sharedObjects.some(isFileMusl)) { +function isMusl() { + // For Node 10 + if (!process.report || typeof process.report.getReport !== 'function') { + try { + const lddPath = require('child_process').execSync('which ldd').toString().trim() + return readFileSync(lddPath, 'utf8').includes('musl') + } catch (e) { return true } - } - return false -} - -const isMuslFromChildProcess = () => { - try { - return require('child_process').execSync('ldd --version', { encoding: 'utf8' }).includes('musl') - } catch (e) { - // If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false - return false + } else { + const { glibcVersionRuntime } = process.report.getReport().header + return !glibcVersionRuntime } } -function requireNative() { - if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) { - try { - return require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH); - } catch (err) { - loadErrors.push(err) - } - } else if (process.platform === 'android') { - if (process.arch === 'arm64') { - try { - return require('./index.android-arm64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-android-arm64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-android-arm64/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm') { - try { - return require('./index.android-arm-eabi.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-android-arm-eabi') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-android-arm-eabi/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`)) - } - } else if (process.platform === 'win32') { - if (process.arch === 'x64') { - if ((process.config && process.config.variables && process.config.variables.shlib_suffix === 'dll.a') || (process.config && process.config.variables && process.config.variables.node_target_type === 'shared_library')) { - try { - return require('./index.win32-x64-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-win32-x64-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-x64-gnu/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - try { - return require('./index.win32-x64-msvc.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-win32-x64-msvc') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-x64-msvc/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } - } else if (process.arch === 'ia32') { - try { - return require('./index.win32-ia32-msvc.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-win32-ia32-msvc') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-ia32-msvc/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm64') { - try { - return require('./index.win32-arm64-msvc.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-win32-arm64-msvc') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-win32-arm64-msvc/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`)) - } - } else if (process.platform === 'darwin') { - try { - return require('./index.darwin-universal.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-darwin-universal') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-darwin-universal/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - if (process.arch === 'x64') { - try { - return require('./index.darwin-x64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-darwin-x64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-darwin-x64/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm64') { - try { - return require('./index.darwin-arm64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-darwin-arm64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-darwin-arm64/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`)) - } - } else if (process.platform === 'freebsd') { - if (process.arch === 'x64') { - try { - return require('./index.freebsd-x64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-freebsd-x64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-freebsd-x64/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm64') { - try { - return require('./index.freebsd-arm64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-freebsd-arm64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-freebsd-arm64/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`)) - } - } else if (process.platform === 'linux') { - if (process.arch === 'x64') { - if (isMusl()) { +switch (platform) { + case 'android': + switch (arch) { + case 'arm64': + localFileExisted = existsSync(join(__dirname, 'index.android-arm64.node')) try { - return require('./index.linux-x64-musl.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-x64-musl') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-x64-musl/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.android-arm64.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-android-arm64') } - return binding } catch (e) { - loadErrors.push(e) + loadError = e } - } else { + break + case 'arm': + localFileExisted = existsSync(join(__dirname, 'index.android-arm-eabi.node')) try { - return require('./index.linux-x64-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-x64-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-x64-gnu/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.android-arm-eabi.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-android-arm-eabi') } - return binding - } catch (e) { - loadErrors.push(e) - } - } - } else if (process.arch === 'arm64') { - if (isMusl()) { - try { - return require('./index.linux-arm64-musl.node') } catch (e) { - loadErrors.push(e) + loadError = e } + break + default: + throw new Error(`Unsupported architecture on Android ${arch}`) + } + break + case 'win32': + switch (arch) { + case 'x64': + localFileExisted = existsSync( + join(__dirname, 'index.win32-x64-msvc.node') + ) try { - const binding = require('@databricks/databricks-sql-kernel-linux-arm64-musl') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm64-musl/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.win32-x64-msvc.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-win32-x64-msvc') } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - try { - return require('./index.linux-arm64-gnu.node') } catch (e) { - loadErrors.push(e) + loadError = e } + break + case 'ia32': + localFileExisted = existsSync( + join(__dirname, 'index.win32-ia32-msvc.node') + ) try { - const binding = require('@databricks/databricks-sql-kernel-linux-arm64-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm64-gnu/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.win32-ia32-msvc.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-win32-ia32-msvc') } - return binding } catch (e) { - loadErrors.push(e) + loadError = e } - } - } else if (process.arch === 'arm') { - if (isMusl()) { + break + case 'arm64': + localFileExisted = existsSync( + join(__dirname, 'index.win32-arm64-msvc.node') + ) try { - return require('./index.linux-arm-musleabihf.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-arm-musleabihf') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm-musleabihf/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.win32-arm64-msvc.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-win32-arm64-msvc') } - return binding } catch (e) { - loadErrors.push(e) + loadError = e } + break + default: + throw new Error(`Unsupported architecture on Windows: ${arch}`) + } + break + case 'darwin': + localFileExisted = existsSync(join(__dirname, 'index.darwin-universal.node')) + try { + if (localFileExisted) { + nativeBinding = require('./index.darwin-universal.node') } else { - try { - return require('./index.linux-arm-gnueabihf.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-arm-gnueabihf') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-arm-gnueabihf/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } + nativeBinding = require('@databricks/databricks-sql-kernel-darwin-universal') } - } else if (process.arch === 'loong64') { - if (isMusl()) { - try { - return require('./index.linux-loong64-musl.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-loong64-musl') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-loong64-musl/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { + break + } catch {} + switch (arch) { + case 'x64': + localFileExisted = existsSync(join(__dirname, 'index.darwin-x64.node')) try { - return require('./index.linux-loong64-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-loong64-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-loong64-gnu/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.darwin-x64.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-darwin-x64') } - return binding - } catch (e) { - loadErrors.push(e) - } - } - } else if (process.arch === 'riscv64') { - if (isMusl()) { - try { - return require('./index.linux-riscv64-musl.node') } catch (e) { - loadErrors.push(e) + loadError = e } + break + case 'arm64': + localFileExisted = existsSync( + join(__dirname, 'index.darwin-arm64.node') + ) try { - const binding = require('@databricks/databricks-sql-kernel-linux-riscv64-musl') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-riscv64-musl/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + if (localFileExisted) { + nativeBinding = require('./index.darwin-arm64.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-darwin-arm64') } - return binding } catch (e) { - loadErrors.push(e) + loadError = e } + break + default: + throw new Error(`Unsupported architecture on macOS: ${arch}`) + } + break + case 'freebsd': + if (arch !== 'x64') { + throw new Error(`Unsupported architecture on FreeBSD: ${arch}`) + } + localFileExisted = existsSync(join(__dirname, 'index.freebsd-x64.node')) + try { + if (localFileExisted) { + nativeBinding = require('./index.freebsd-x64.node') } else { - try { - return require('./index.linux-riscv64-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-riscv64-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-riscv64-gnu/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } - } else if (process.arch === 'ppc64') { - try { - return require('./index.linux-ppc64-gnu.node') - } catch (e) { - loadErrors.push(e) + nativeBinding = require('@databricks/databricks-sql-kernel-freebsd-x64') } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-ppc64-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-ppc64-gnu/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 's390x') { - try { - return require('./index.linux-s390x-gnu.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-linux-s390x-gnu') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-linux-s390x-gnu/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`)) + } catch (e) { + loadError = e } - } else if (process.platform === 'openharmony') { - if (process.arch === 'arm64') { - try { - return require('./index.openharmony-arm64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-openharmony-arm64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-openharmony-arm64/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) - } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'x64') { - try { - return require('./index.openharmony-x64.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-openharmony-x64') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-openharmony-x64/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + break + case 'linux': + switch (arch) { + case 'x64': + if (isMusl()) { + localFileExisted = existsSync( + join(__dirname, 'index.linux-x64-musl.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-x64-musl.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-x64-musl') + } + } catch (e) { + loadError = e + } + } else { + localFileExisted = existsSync( + join(__dirname, 'index.linux-x64-gnu.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-x64-gnu.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-x64-gnu') + } + } catch (e) { + loadError = e + } } - return binding - } catch (e) { - loadErrors.push(e) - } - } else if (process.arch === 'arm') { - try { - return require('./index.openharmony-arm.node') - } catch (e) { - loadErrors.push(e) - } - try { - const binding = require('@databricks/databricks-sql-kernel-openharmony-arm') - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-openharmony-arm/package.json').version - if (bindingPackageVersion !== '1.4.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - throw new Error(`Native binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + break + case 'arm64': + if (isMusl()) { + localFileExisted = existsSync( + join(__dirname, 'index.linux-arm64-musl.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-arm64-musl.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm64-musl') + } + } catch (e) { + loadError = e + } + } else { + localFileExisted = existsSync( + join(__dirname, 'index.linux-arm64-gnu.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-arm64-gnu.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm64-gnu') + } + } catch (e) { + loadError = e + } } - return binding - } catch (e) { - loadErrors.push(e) - } - } else { - loadErrors.push(new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`)) - } - } else { - loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`)) - } -} - -function createLoadErrorChain(errors) { - return errors.reduce((previous, current) => { - let message - try { - message = - current && typeof current.message === 'string' - ? current.message - : String(current) - } catch { - message = 'Unknown error' - } - const error = new Error(message) - error.cause = previous - return error - }, null) -} - -// NAPI_RS_FORCE_WASI is a tri-state flag: -// unset / any other value → native binding preferred, WASI is only a fallback -// 'true' → prefer WASI, but retain native as a lazy fallback -// 'error' → require WASI without initializing a native fallback -// Treating any non-empty string as truthy (the historical behavior) meant -// NAPI_RS_FORCE_WASI=false, NAPI_RS_FORCE_WASI=0, etc. inadvertently triggered -// the WASI path, causing ENOENT for packages shipped without a .wasi.cjs file. -// -// NAPI_RS_WASI_FLAVOR selects one exact generated flavor and implies strict -// WASI loading. It never crosses into another flavor or falls back to native. -const __napiWasiFlavors = ["wasm32-wasi"] -const __napiWasiFlavor = process.env.NAPI_RS_WASI_FLAVOR -const __napiWasiFlavorRequested = - typeof __napiWasiFlavor === 'string' && __napiWasiFlavor.length > 0 -if ( - __napiWasiFlavorRequested && - __napiWasiFlavors.indexOf(__napiWasiFlavor) === -1 -) { - throw new Error( - 'Unsupported WASI flavor "' + - __napiWasiFlavor + - '". Available flavors: ' + - __napiWasiFlavors.join(', '), - ) -} -const forceWasiError = process.env.NAPI_RS_FORCE_WASI === 'error' -const forceWasi = - process.env.NAPI_RS_FORCE_WASI === 'true' || - forceWasiError || - __napiWasiFlavorRequested - -if (!forceWasi) { - nativeBinding = requireNative() -} - -if (!nativeBinding || forceWasi) { - let wasiBinding = null - let wasiBindingLoaded = false - const wasiBindingErrors = [] - const __napiWasiResolveCandidate = (specifier, isPackage, localArtifacts) => { - try { - require.resolve(specifier) - } catch (resolveError) { - if (!resolveError || resolveError.code !== 'MODULE_NOT_FOUND') { - throw resolveError - } - if (isPackage) { - try { - require.resolve(specifier + '/package.json') - } catch (packageError) { - if (packageError && packageError.code === 'MODULE_NOT_FOUND') { - return resolveError + break + case 'arm': + if (isMusl()) { + localFileExisted = existsSync( + join(__dirname, 'index.linux-arm-musleabihf.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-arm-musleabihf.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm-musleabihf') + } + } catch (e) { + loadError = e + } + } else { + localFileExisted = existsSync( + join(__dirname, 'index.linux-arm-gnueabihf.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-arm-gnueabihf.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-arm-gnueabihf') + } + } catch (e) { + loadError = e } - // An exports restriction proves the package exists even when its - // package.json is not public. Preserve the root resolution failure. - throw resolveError } - // The package exists but its main/export target is broken. - throw resolveError - } - return resolveError - } - if (localArtifacts) { - let artifactError = null - for (let i = 0; i < localArtifacts.length; i++) { - try { - require.resolve(localArtifacts[i]) - return null - } catch (resolveError) { - if (!resolveError || resolveError.code !== 'MODULE_NOT_FOUND') { - throw resolveError + break + case 'riscv64': + if (isMusl()) { + localFileExisted = existsSync( + join(__dirname, 'index.linux-riscv64-musl.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-riscv64-musl.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-riscv64-musl') + } + } catch (e) { + loadError = e + } + } else { + localFileExisted = existsSync( + join(__dirname, 'index.linux-riscv64-gnu.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-riscv64-gnu.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-riscv64-gnu') + } + } catch (e) { + loadError = e } - artifactError = resolveError } - } - return artifactError - } - return null - } - if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === "wasm32-wasi")) { - let candidateError = null - let candidateFailed = false - try { - candidateError = __napiWasiResolveCandidate('./index.wasi.cjs', false, ["./index.wasm32-wasi.debug.wasm","./index.wasm32-wasi.wasm"]) - candidateFailed = candidateError !== null - if (!candidateFailed) { - wasiBinding = require('./index.wasi.cjs') - nativeBinding = wasiBinding - wasiBindingLoaded = true - } - } catch (err) { - candidateError = err - candidateFailed = true - } - if (candidateFailed) { - wasiBindingErrors.push(candidateError) - loadErrors.push(candidateError) - } - } - if (!wasiBindingLoaded && (!__napiWasiFlavorRequested || __napiWasiFlavor === "wasm32-wasi")) { - let candidateError = null - let candidateFailed = false - try { - candidateError = __napiWasiResolveCandidate('@databricks/databricks-sql-kernel-wasm32-wasi', true, undefined) - candidateFailed = candidateError !== null - if (!candidateFailed) { - if (process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { - const bindingPackageVersion = require('@databricks/databricks-sql-kernel-wasm32-wasi/package.json').version - if (bindingPackageVersion !== '1.4.0') { - throw new Error(`WASI binding package version mismatch, expected 1.4.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + break + case 's390x': + localFileExisted = existsSync( + join(__dirname, 'index.linux-s390x-gnu.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./index.linux-s390x-gnu.node') + } else { + nativeBinding = require('@databricks/databricks-sql-kernel-linux-s390x-gnu') } + } catch (e) { + loadError = e } - wasiBinding = require('@databricks/databricks-sql-kernel-wasm32-wasi') - nativeBinding = wasiBinding - wasiBindingLoaded = true - } - } catch (err) { - candidateError = err - candidateFailed = true + break + default: + throw new Error(`Unsupported architecture on Linux: ${arch}`) } - if (candidateFailed) { - wasiBindingErrors.push(candidateError) - loadErrors.push(candidateError) - } - } - if ( - !wasiBindingLoaded && - forceWasi && - !forceWasiError && - !__napiWasiFlavorRequested - ) { - nativeBinding = requireNative() - } - if ((forceWasiError || __napiWasiFlavorRequested) && !wasiBindingLoaded) { - const error = new Error( - __napiWasiFlavorRequested - ? 'WASI binding for flavor "' + __napiWasiFlavor + '" not found' - : 'WASI binding not found and NAPI_RS_FORCE_WASI is set to error', - ) - error.cause = createLoadErrorChain(wasiBindingErrors) - throw error - } + break + default: + throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`) } if (!nativeBinding) { - if (loadErrors.length > 0) { - const error = new Error( - `Cannot find native binding. ` + - `npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). ` + - 'Please try `npm i` again after removing both package-lock.json and node_modules directory.', - ) - // assign instead of the `new Error(message, { cause })` options form, - // which Node < 16.9 silently ignores - error.cause = createLoadErrorChain(loadErrors) - throw error + if (loadError) { + throw loadError } throw new Error(`Failed to load native binding`) } -module.exports = nativeBinding -module.exports.AsyncResultHandle = nativeBinding.AsyncResultHandle -module.exports.AsyncStatement = nativeBinding.AsyncStatement -module.exports.CancellableExecution = nativeBinding.CancellableExecution -module.exports.Connection = nativeBinding.Connection -module.exports.Statement = nativeBinding.Statement -module.exports.AuthMode = nativeBinding.AuthMode -module.exports.initKernelLogging = nativeBinding.initKernelLogging -module.exports.kernelLoggingStats = nativeBinding.kernelLoggingStats -module.exports.openSession = nativeBinding.openSession -module.exports.setKernelLogLevel = nativeBinding.setKernelLogLevel -module.exports.version = nativeBinding.version +const { AsyncStatement, AsyncResultHandle, CancellableExecution, Connection, AuthMode, openSession, initKernelLogging, kernelLoggingStats, setKernelLogLevel, Statement, version } = nativeBinding + +module.exports.AsyncStatement = AsyncStatement +module.exports.AsyncResultHandle = AsyncResultHandle +module.exports.CancellableExecution = CancellableExecution +module.exports.Connection = Connection +module.exports.AuthMode = AuthMode +module.exports.openSession = openSession +module.exports.initKernelLogging = initKernelLogging +module.exports.kernelLoggingStats = kernelLoggingStats +module.exports.setKernelLogLevel = setKernelLogLevel +module.exports.Statement = Statement +module.exports.version = version From e9eb91072202d812f4613eae6b72ec18f1a5084e Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sun, 15 Nov 2026 08:53:24 +0000 Subject: [PATCH 10/11] test(cloudfetch): a same-URL refresh clears the refusal Review follow-up. When a refresh returns the refused URL unchanged and the next failure is not a refusal, the retry reuses the URL without a second refresh; the test fails if the post-refresh reset of the refused URL is removed. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- src/reader/cloudfetch/streaming_provider.rs | 109 ++++++++++++++++++++ 1 file changed, 109 insertions(+) diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index 96f988f2..92a164ff 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -2255,6 +2255,115 @@ mod tests { ); } + #[tokio::test] + async fn refresh_that_returns_the_same_url_clears_the_refusal() { + use crate::client::retry::{build_retry_configs, RetryConfig}; + use crate::client::{DatabricksHttpClient, HttpClientConfig}; + use crate::types::sea::CompressionCodec; + use arrow_array::Int32Array; + use arrow_ipc::writer::StreamWriter; + use arrow_schema::{DataType, Field, Schema}; + use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; + use wiremock::matchers::method; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![1]))]) + .unwrap(); + let mut ipc_bytes = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut ipc_bytes, &schema).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + } + + // 403, then a 500 (not a refusal), then success, all on the same URL. + let server = MockServer::start().await; + for status in [403, 500] { + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(status)) + .up_to_n_times(1) + .mount(&server) + .await; + } + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(ipc_bytes)) + .mount(&server) + .await; + + #[derive(Debug)] + struct SameUrlFetcher { + url: String, + refresh_calls: AtomicUsize, + } + + #[async_trait::async_trait] + impl ChunkLinkFetcher for SameUrlFetcher { + async fn fetch_links(&self, _: i64, _: i64) -> Result { + unreachable!() + } + + async fn refetch_link(&self, _: i64, _: i64) -> Result { + unreachable!() + } + + async fn refetch_links_from(&self, _: i64, _: i64) -> Result> { + self.refresh_calls.fetch_add(1, AtomicOrdering::SeqCst); + Ok(vec![CloudFetchLink { + url: self.url.clone(), + ..create_test_link(0) + }]) + } + } + + let retry = RetryConfig { + max_retries: 0, + ..RetryConfig::default() + }; + let http_client = Arc::new( + DatabricksHttpClient::new( + HttpClientConfig::default(), + build_retry_configs(&retry, &HashMap::new()), + ) + .unwrap(), + ); + let url = format!("{}/chunk-0.arrow", server.uri()); + let fetcher = Arc::new(SameUrlFetcher { + url: url.clone(), + refresh_calls: AtomicUsize::new(0), + }); + let chunks = Arc::new(DashMap::new()); + let original = CloudFetchLink { + url, + ..create_test_link(0) + }; + chunks.insert(0, entry_with_state(original, ChunkState::Downloading)); + let ctx = DownloadCtx { + downloader: Arc::new(ChunkDownloader::new( + http_client, + CompressionCodec::None, + 0.1, + )), + link_fetcher: fetcher.clone(), + chunks, + refresh_coordinator: Arc::new(RefreshCoordinator::default()), + cancel_token: CancellationToken::new(), + statement_id: None, + metrics: Arc::new(CloudFetchMetrics::new(Some(1))), + max_retries: 5, + retry_delay: std::time::Duration::ZERO, + download_timeout: std::time::Duration::ZERO, + }; + + StreamingCloudFetchProvider::download_chunk_with_retry(0, &ctx) + .await + .expect("the third download succeeds"); + assert_eq!(server.received_requests().await.unwrap().len(), 3); + // The refreshed URL is no longer treated as refused, so the 500 retry + // reuses it without a second refresh. + assert_eq!(fetcher.refresh_calls.load(AtomicOrdering::SeqCst), 1); + } + #[tokio::test] async fn refused_url_with_failing_refresh_surfaces_the_refresh_error() { use crate::client::retry::{build_retry_configs, RetryConfig}; From db0ee024c64a0a63c3e92d6164800cd29c1f5953 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Mon, 16 Nov 2026 01:58:37 +0000 Subject: [PATCH 11/11] fix(cloudfetch): mark a refused link expired instead of tracking it Scope trim. A 401/403/404 download now marks the cached link expired, so the existing expiry path refreshes it on the next attempt, after the usual retry delay. This replaces the rejected-URL state, the refresh variant and its dedupe predicate, the first-refusal fast path and its log, and the tests that covered only those. Production change vs main: +12 lines. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- src/reader/cloudfetch/streaming_provider.rs | 378 +------------------- 1 file changed, 19 insertions(+), 359 deletions(-) diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index 92a164ff..99398e18 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -927,9 +927,8 @@ impl StreamingCloudFetchProvider { )) } - /// Download a single chunk with retry, refreshing the link when it expires - /// or storage refuses it (401/403/404), bounded end-to-end by - /// [`CloudFetchConfig::download_timeout`]. + /// Download a single chunk with retry and link refresh on expiry, + /// bounded end-to-end by [`CloudFetchConfig::download_timeout`]. async fn download_chunk_with_retry( chunk_index: i64, ctx: &DownloadCtx, @@ -945,11 +944,6 @@ impl StreamingCloudFetchProvider { let deadline = (!ctx.download_timeout.is_zero()) .then(|| std::time::Instant::now() + ctx.download_timeout); - // A presigned URL cloud storage refused (401/403/404). The next attempt - // refreshes the link even though it has not expired. - let mut rejected_url: Option = None; - let mut refused_before = false; - loop { if ctx.cancel_token.is_cancelled() { return Err(Error::invalid_state().message("Download cancelled")); @@ -980,21 +974,12 @@ impl StreamingCloudFetchProvider { let stored_link = ctx.chunks.get(&chunk_index).and_then(|e| e.link.clone()); match stored_link { - Some(link) - if !link.is_expired() - && rejected_url.as_deref() != Some(link.url.as_str()) => - { - link - } + Some(link) if !link.is_expired() => link, _ => { debug!( - "Link for chunk {} {}; triggering batched refresh", - chunk_index, - if rejected_url.is_some() { - "rejected by storage" - } else { - "missing or expired" - } + "Link for chunk {} missing or expired; \ + triggering batched refresh", + chunk_index ); // Bound the refresh RPC by the remaining chunk // budget so a stalled refresh can't overshoot the @@ -1003,9 +988,8 @@ impl StreamingCloudFetchProvider { // keeps the deadline genuinely end-to-end across // the link-refresh step, matching the loop-level // comment above. - let refresh = Self::refresh_links_batch_replacing( + let refresh = Self::refresh_links_batch( chunk_index, - rejected_url.as_deref(), &ctx.link_fetcher, &ctx.chunks, &ctx.refresh_coordinator, @@ -1036,9 +1020,6 @@ impl StreamingCloudFetchProvider { )) .with_cause(e) })?; - // Download whatever URL the refresh produced; a - // repeat rejection is charged to the attempt budget. - rejected_url = None; // After a successful refresh, the link // MUST exist and be fresh — `refresh_links_batch` // returns Err otherwise (missing chunk in @@ -1143,22 +1124,16 @@ impl StreamingCloudFetchProvider { if attempts >= ctx.max_retries { return Err(e); } - // Storage refused the presigned URL itself (an expired or - // invalid signature; GCS answers 404 for an expired one), so - // retrying it cannot succeed: refresh the link instead. The - // first refusal refreshes at once; if a refreshed URL is refused - // too, fall through to the backoff below before refreshing again. - if let Some(status @ (401 | 403 | 404)) = e.http_status { - rejected_url = Some(link.url.clone()); - if !refused_before { - refused_before = true; - // Later refusals are logged by the retry warning below. - warn!( - "Chunk {} download refused with HTTP {} (attempt {}/{}): {}, \ - refreshing the link", - chunk_index, status, attempts, ctx.max_retries, e - ); - continue; + // Storage refused the presigned URL itself (an expired or invalid + // signature; GCS answers 404 for an expired one), so retrying it + // cannot succeed. Mark the cached link expired: the next attempt + // then refreshes it through the usual expiry path. + if matches!(e.http_status, Some(401 | 403 | 404)) { + if let Some(mut entry) = ctx.chunks.get_mut(&chunk_index) { + if let Some(cached) = entry.link.as_mut().filter(|l| l.url == link.url) + { + cached.expiration = chrono::Utc::now(); + } } } // Stale-snapshot detection. Two ways a download @@ -1325,34 +1300,6 @@ impl StreamingCloudFetchProvider { cancel_token: &CancellationToken, statement_id: Option<&str>, ) -> Result<()> { - Self::refresh_links_batch_replacing( - start_chunk_index, - None, - link_fetcher, - chunks, - coordinator, - cancel_token, - statement_id, - ) - .await - } - - /// [`Self::refresh_links_batch`], where `rejected_url` (when set) is a - /// presigned URL cloud storage refused: a cached link with that URL needs - /// a refresh even though it has not expired. - async fn refresh_links_batch_replacing( - start_chunk_index: i64, - rejected_url: Option<&str>, - link_fetcher: &Arc, - chunks: &Arc>, - coordinator: &Arc, - cancel_token: &CancellationToken, - statement_id: Option<&str>, - ) -> Result<()> { - // A cached link is usable unless it expired or storage rejected its URL. - let is_usable = |link: &crate::types::CloudFetchLink| { - !link.is_expired() && rejected_url != Some(link.url.as_str()) - }; // Display helper: `""` is loud enough for ops // to notice missing statement_id in log filters. let sid = statement_id.unwrap_or(""); @@ -1426,7 +1373,7 @@ impl StreamingCloudFetchProvider { let url_changed = pre_attempt_url .as_ref() .is_some_and(|prev| *prev != link.url); - if url_changed || is_usable(link) { + if url_changed || !link.is_expired() { debug!( statement_id = %sid, "Concurrent refresh delivered a {} link for chunk {}; \ @@ -1476,7 +1423,7 @@ impl StreamingCloudFetchProvider { let url_changed = pre_attempt_url .as_ref() .is_some_and(|prev| *prev != link.url); - if url_changed || is_usable(link) { + if url_changed || !link.is_expired() { debug!( statement_id = %sid, "Batched refresh for chunk {} skipped after claim — \ @@ -2157,213 +2104,6 @@ mod tests { ); } - #[tokio::test] - async fn repeatedly_refused_url_backs_off_before_refreshing_again() { - use crate::client::retry::{build_retry_configs, RetryConfig}; - use crate::client::{DatabricksHttpClient, HttpClientConfig}; - use crate::types::sea::CompressionCodec; - use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; - use wiremock::matchers::method; - use wiremock::{Mock, MockServer, ResponseTemplate}; - - // Long enough that the < 2 × delay bound leaves a wide margin for the round-trips. - const RETRY_DELAY: std::time::Duration = std::time::Duration::from_secs(1); - - // Storage refuses every URL, including refreshed ones. - let server = MockServer::start().await; - Mock::given(method("GET")) - .respond_with(ResponseTemplate::new(403)) - .mount(&server) - .await; - - #[derive(Debug)] - struct NewUrlFetcher { - base: String, - refresh_calls: AtomicUsize, - } - - #[async_trait::async_trait] - impl ChunkLinkFetcher for NewUrlFetcher { - async fn fetch_links(&self, _: i64, _: i64) -> Result { - unreachable!() - } - - async fn refetch_link(&self, _: i64, _: i64) -> Result { - unreachable!() - } - - async fn refetch_links_from(&self, _: i64, _: i64) -> Result> { - let n = self.refresh_calls.fetch_add(1, AtomicOrdering::SeqCst) + 1; - Ok(vec![CloudFetchLink { - url: format!("{}/chunk-0-{n}.arrow", self.base), - ..create_test_link(0) - }]) - } - } - - let retry = RetryConfig { - max_retries: 0, - ..RetryConfig::default() - }; - let http_client = Arc::new( - DatabricksHttpClient::new( - HttpClientConfig::default(), - build_retry_configs(&retry, &HashMap::new()), - ) - .unwrap(), - ); - let fetcher = Arc::new(NewUrlFetcher { - base: server.uri(), - refresh_calls: AtomicUsize::new(0), - }); - let chunks = Arc::new(DashMap::new()); - let original = CloudFetchLink { - url: format!("{}/chunk-0-0.arrow", server.uri()), - ..create_test_link(0) - }; - chunks.insert(0, entry_with_state(original, ChunkState::Downloading)); - let ctx = DownloadCtx { - downloader: Arc::new(ChunkDownloader::new( - http_client, - CompressionCodec::None, - 0.1, - )), - link_fetcher: fetcher.clone(), - chunks, - refresh_coordinator: Arc::new(RefreshCoordinator::default()), - cancel_token: CancellationToken::new(), - statement_id: None, - metrics: Arc::new(CloudFetchMetrics::new(Some(1))), - max_retries: 3, - retry_delay: RETRY_DELAY, - download_timeout: std::time::Duration::ZERO, - }; - - let started = std::time::Instant::now(); - let error = StreamingCloudFetchProvider::download_chunk_with_retry(0, &ctx) - .await - .expect_err("a URL storage always refuses must fail"); - let elapsed = started.elapsed(); - assert_eq!(error.http_status, Some(403)); - assert_eq!(server.received_requests().await.unwrap().len(), 3); - assert_eq!(fetcher.refresh_calls.load(AtomicOrdering::SeqCst), 2); - // Exactly one backoff: the first refusal refreshes at once, and only the - // refused refreshed URL waits before the next refresh. - assert!( - elapsed >= RETRY_DELAY && elapsed < RETRY_DELAY * 2, - "expected exactly one backoff of {RETRY_DELAY:?}, took {elapsed:?}" - ); - } - - #[tokio::test] - async fn refresh_that_returns_the_same_url_clears_the_refusal() { - use crate::client::retry::{build_retry_configs, RetryConfig}; - use crate::client::{DatabricksHttpClient, HttpClientConfig}; - use crate::types::sea::CompressionCodec; - use arrow_array::Int32Array; - use arrow_ipc::writer::StreamWriter; - use arrow_schema::{DataType, Field, Schema}; - use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; - use wiremock::matchers::method; - use wiremock::{Mock, MockServer, ResponseTemplate}; - - let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); - let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![1]))]) - .unwrap(); - let mut ipc_bytes = Vec::new(); - { - let mut writer = StreamWriter::try_new(&mut ipc_bytes, &schema).unwrap(); - writer.write(&batch).unwrap(); - writer.finish().unwrap(); - } - - // 403, then a 500 (not a refusal), then success, all on the same URL. - let server = MockServer::start().await; - for status in [403, 500] { - Mock::given(method("GET")) - .respond_with(ResponseTemplate::new(status)) - .up_to_n_times(1) - .mount(&server) - .await; - } - Mock::given(method("GET")) - .respond_with(ResponseTemplate::new(200).set_body_bytes(ipc_bytes)) - .mount(&server) - .await; - - #[derive(Debug)] - struct SameUrlFetcher { - url: String, - refresh_calls: AtomicUsize, - } - - #[async_trait::async_trait] - impl ChunkLinkFetcher for SameUrlFetcher { - async fn fetch_links(&self, _: i64, _: i64) -> Result { - unreachable!() - } - - async fn refetch_link(&self, _: i64, _: i64) -> Result { - unreachable!() - } - - async fn refetch_links_from(&self, _: i64, _: i64) -> Result> { - self.refresh_calls.fetch_add(1, AtomicOrdering::SeqCst); - Ok(vec![CloudFetchLink { - url: self.url.clone(), - ..create_test_link(0) - }]) - } - } - - let retry = RetryConfig { - max_retries: 0, - ..RetryConfig::default() - }; - let http_client = Arc::new( - DatabricksHttpClient::new( - HttpClientConfig::default(), - build_retry_configs(&retry, &HashMap::new()), - ) - .unwrap(), - ); - let url = format!("{}/chunk-0.arrow", server.uri()); - let fetcher = Arc::new(SameUrlFetcher { - url: url.clone(), - refresh_calls: AtomicUsize::new(0), - }); - let chunks = Arc::new(DashMap::new()); - let original = CloudFetchLink { - url, - ..create_test_link(0) - }; - chunks.insert(0, entry_with_state(original, ChunkState::Downloading)); - let ctx = DownloadCtx { - downloader: Arc::new(ChunkDownloader::new( - http_client, - CompressionCodec::None, - 0.1, - )), - link_fetcher: fetcher.clone(), - chunks, - refresh_coordinator: Arc::new(RefreshCoordinator::default()), - cancel_token: CancellationToken::new(), - statement_id: None, - metrics: Arc::new(CloudFetchMetrics::new(Some(1))), - max_retries: 5, - retry_delay: std::time::Duration::ZERO, - download_timeout: std::time::Duration::ZERO, - }; - - StreamingCloudFetchProvider::download_chunk_with_retry(0, &ctx) - .await - .expect("the third download succeeds"); - assert_eq!(server.received_requests().await.unwrap().len(), 3); - // The refreshed URL is no longer treated as refused, so the 500 retry - // reuses it without a second refresh. - assert_eq!(fetcher.refresh_calls.load(AtomicOrdering::SeqCst), 1); - } - #[tokio::test] async fn refused_url_with_failing_refresh_surfaces_the_refresh_error() { use crate::client::retry::{build_retry_configs, RetryConfig}; @@ -3440,86 +3180,6 @@ mod tests { ); } - #[tokio::test] - async fn refresh_waiter_does_not_take_a_rejected_link_as_fresh() { - // Chunk 0's link has not expired, but storage rejected its URL. Another - // task holds the refresh claim and finishes without touching chunk 0, so - // the waiter must still issue its own refresh instead of skipping it. - let rejected = create_test_link(0); - let chunks: Arc> = Arc::new(DashMap::new()); - chunks.insert( - 0, - entry_with_state(rejected.clone(), ChunkState::Downloading), - ); - let mock = RefreshCountingMock::new(1); - let coordinator = Arc::new(RefreshCoordinator::default()); - coordinator.in_progress.store(true, Ordering::Release); - - let fetcher: Arc = mock.clone(); - let (task_chunks, task_coordinator) = (Arc::clone(&chunks), Arc::clone(&coordinator)); - let rejected_url = rejected.url.clone(); - let waiter = tokio::spawn(async move { - StreamingCloudFetchProvider::refresh_links_batch_replacing( - 0, - Some(&rejected_url), - &fetcher, - &task_chunks, - &task_coordinator, - &CancellationToken::new(), - None, - ) - .await - }); - // On the single-threaded test runtime one yield runs the waiter until it parks on `done`. - tokio::task::yield_now().await; - assert!( - !waiter.is_finished(), - "the waiter must wait for the other refresh" - ); - coordinator.in_progress.store(false, Ordering::Release); - coordinator.done.notify_waiters(); - - waiter.await.unwrap().unwrap(); - assert_eq!(mock.refresh_calls.load(AtomicOrdering::SeqCst), 1); - assert_ne!( - chunks.get(&0).unwrap().link.as_ref().unwrap().url, - rejected.url, - "the rejected URL must be replaced" - ); - } - - #[tokio::test] - async fn refresh_skips_a_rejected_url_another_task_already_replaced() { - // Storage refused chunk 0's original URL, but another task has already - // cached a fresh one, so no refresh RPC is needed. - let rejected = create_test_link(0); - let replaced = RefreshCountingMock::fresh_link(0); - let chunks: Arc> = Arc::new(DashMap::new()); - chunks.insert( - 0, - entry_with_state(replaced.clone(), ChunkState::Downloading), - ); - let mock = RefreshCountingMock::new(1); - let fetcher: Arc = mock.clone(); - - StreamingCloudFetchProvider::refresh_links_batch_replacing( - 0, - Some(&rejected.url), - &fetcher, - &chunks, - &Arc::new(RefreshCoordinator::default()), - &CancellationToken::new(), - None, - ) - .await - .unwrap(); - assert_eq!(mock.refresh_calls.load(AtomicOrdering::SeqCst), 0); - assert_eq!( - chunks.get(&0).unwrap().link.as_ref().unwrap().url, - replaced.url - ); - } - #[tokio::test] async fn refresh_batch_disjoint_window_loser_retries_claim() { // Loser-of-claim disjoint-window gap (round-3 follow-up):