From a05b118dd85d7be4c37b48b04801eb43f5e20dc4 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sat, 14 Nov 2026 04:26:40 +0000 Subject: [PATCH 1/9] fix(cloudfetch): advance link prefetch with scheduled downloads Signed-off-by: Aakash Saravanan --- src/reader/cloudfetch/link_fetcher.rs | 53 +++++++++++-- src/reader/cloudfetch/streaming_provider.rs | 82 +++++++++++++++++++++ 2 files changed, 128 insertions(+), 7 deletions(-) diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 8bbcdb6a..070cc3f7 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -66,6 +66,9 @@ use tokio::sync::Mutex as TokioMutex; /// Both parameters are passed to methods; implementations use the relevant one. #[async_trait] pub(crate) trait ChunkLinkFetcher: Send + Sync + std::fmt::Debug { + // Cached links can outlive a fetch call, so scheduling must advance the prefetch horizon. + fn note_scheduled(&self, _chunk_index: i64) {} + /// Fetch the next batch of chunk links. /// /// # Parameters @@ -875,6 +878,13 @@ impl SeaChunkLinkFetcherHandle { #[async_trait] impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { + fn note_scheduled(&self, chunk_index: i64) { + self.inner + .current_consumer_index + .fetch_max(chunk_index, Ordering::Release); + self.inner.maybe_trigger_prefetch(); + } + async fn fetch_links( &self, start_chunk_index: i64, @@ -882,13 +892,7 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { ) -> Result { let fetcher = &self.inner; - // Update consumer position (highest chunk index requested) - fetcher - .current_consumer_index - .fetch_max(start_chunk_index, Ordering::Release); - - // Trigger async prefetch if needed (non-blocking) - self.inner.maybe_trigger_prefetch(); + self.note_scheduled(start_chunk_index); // If we already have all links, return what we have from cache. // Walk contiguously from `start_chunk_index` until we hit a @@ -1434,6 +1438,41 @@ mod tests { assert_eq!(result.next_chunk_index, None); } + #[tokio::test] + async fn scheduled_cached_links_advance_bounded_prefetch() { + let pages: Vec<_> = (0..8).map(|i| vec![create_test_link(i)]).collect(); + let initial: Vec<_> = (0..4).map(create_test_link).collect(); + let fetcher = SeaChunkLinkFetcher::new( + Arc::new(MockDatabricksClient::new(pages)), + "test-statement", + &initial, + Some(8), + 2, + tokio::runtime::Handle::current(), + SessionAttribution::Current, + ); + let handle = SeaChunkLinkFetcherHandle::new(fetcher); + assert!(!handle.inner.has_link(4)); + + handle.note_scheduled(2); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while handle.inner.prefetch_in_progress.load(Ordering::Acquire) { + tokio::task::yield_now().await; + } + }) + .await + .expect("scheduling cached chunk 2 must prefetch the next page"); + + assert!(handle.inner.has_link(3)); + assert!(handle.inner.has_link(4)); + assert!(!handle.inner.has_link(5)); + handle.note_scheduled(1); + assert_eq!( + handle.inner.current_consumer_index.load(Ordering::Acquire), + 2 + ); + } + #[tokio::test] async fn test_sea_link_fetcher_with_initial_links() { let links = vec![ diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index 5fbab8d7..9c536ea7 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -820,6 +820,7 @@ impl StreamingCloudFetchProvider { // Increment counters let new_count = self.chunks_in_memory.fetch_add(1, Ordering::Release) + 1; self.next_download_index.fetch_add(1, Ordering::Release); + self.link_fetcher.note_scheduled(next_index); debug!( "Scheduling download for chunk {}: chunks_in_memory={}/{}, consumer_at={}", @@ -1728,6 +1729,7 @@ mod tests { struct MockLinkFetcher { links_by_index: HashMap, total_chunks: i64, + scheduled: Mutex>, } impl MockLinkFetcher { @@ -1740,12 +1742,17 @@ mod tests { Self { links_by_index, total_chunks, + scheduled: Mutex::new(Vec::new()), } } } #[async_trait::async_trait] impl ChunkLinkFetcher for MockLinkFetcher { + fn note_scheduled(&self, chunk_index: i64) { + self.scheduled.lock().unwrap().push(chunk_index); + } + async fn fetch_links( &self, start_chunk_index: i64, @@ -1818,6 +1825,81 @@ mod tests { } } + #[tokio::test] + async fn bounded_downloads_notify_each_scheduled_chunk_in_order() { + use crate::client::retry::{build_retry_configs, RetryConfig}; + use crate::client::{DatabricksHttpClient, HttpClientConfig}; + use crate::types::sea::CompressionCodec; + use arrow_ipc::writer::StreamWriter; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + let mut fetcher = MockLinkFetcher::new(8); + for i in 0..8 { + let batch = make_batch(&[i as i32]); + let mut bytes = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + } + let route = format!("/chunk-{i}"); + Mock::given(method("GET")) + .and(path(&route)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + .expect(1) + .mount(&server) + .await; + fetcher.links_by_index.get_mut(&i).unwrap().url = format!("{}{route}", server.uri()); + } + let fetcher = Arc::new(fetcher); + let client = DatabricksHttpClient::new( + HttpClientConfig::default(), + build_retry_configs( + &RetryConfig { + max_retries: 0, + ..RetryConfig::default() + }, + &HashMap::new(), + ), + ) + .unwrap(); + let provider = StreamingCloudFetchProvider::new( + CloudFetchConfig { + max_chunks_in_memory: 2, + ..CloudFetchConfig::default() + }, + fetcher.clone(), + Arc::new(ChunkDownloader::new( + Arc::new(client), + CompressionCodec::None, + 0.1, + )), + Some(8), + tokio::runtime::Handle::current(), + ); + let mut values = Vec::new(); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while let Some(batch) = provider.next_batch().await.unwrap() { + let ids = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + values.extend_from_slice(ids.values()); + assert!(provider.chunks_in_memory.load(Ordering::Acquire) <= 2); + } + }) + .await + .expect("all eight chunks must drain with a two-chunk window"); + assert_eq!(values, (0..8).collect::>()); + assert_eq!( + *fetcher.scheduled.lock().unwrap(), + (0..8).collect::>() + ); + } + /// Regression (PECOBLR-4026): a panicking download task must surface as an /// error rather than being silently swallowed — a swallowed panic leaves the /// chunk stuck `Downloading` and wedges the stream forever. Verifies From 6213f3e68fa9cbe2e92acebf70b5ea23be65ce71 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sat, 14 Nov 2026 04:46:22 +0000 Subject: [PATCH 2/9] fix(cloudfetch): share prefetched pages with waiting readers Signed-off-by: Aakash Saravanan --- src/reader/cloudfetch/link_fetcher.rs | 101 ++++++++++++++++++++++++-- 1 file changed, 96 insertions(+), 5 deletions(-) diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 070cc3f7..008a2dc6 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -223,7 +223,7 @@ pub(crate) struct SeaChunkLinkFetcher { prefetch_in_progress: AtomicBool, /// Tokio runtime handle for spawning prefetch tasks runtime_handle: tokio::runtime::Handle, - /// Lock for coordinating prefetch operations + /// Foreground misses must share pages already being prefetched. prefetch_lock: TokioMutex<()>, /// Next row offset for pagination (used by some backends) next_row_offset: AtomicI64, @@ -721,10 +721,10 @@ impl SeaChunkLinkFetcher { /// Background prefetch loop - fetches links until caught up with window. async fn run_prefetch_loop(self: Arc) { - // Acquire the prefetch lock to prevent concurrent prefetch operations - let _guard = self.prefetch_lock.lock().await; - loop { + // Release between pages so a waiting reader can use the page just fetched. + let _page = self.prefetch_lock.lock().await; + // Check if we're done if self.all_links_fetched.load(Ordering::Acquire) { debug!("Prefetch loop: all links fetched, stopping"); @@ -894,6 +894,14 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { self.note_scheduled(start_chunk_index); + let _fallback = if !fetcher.all_links_fetched.load(Ordering::Acquire) + && start_chunk_index >= fetcher.next_server_fetch_index.load(Ordering::Acquire) + { + Some(fetcher.prefetch_lock.lock().await) + } else { + None + }; + // If we already have all links, return what we have from cache. // Walk contiguously from `start_chunk_index` until we hit a // gap — that handles both the known case (server returned @@ -1133,11 +1141,21 @@ mod tests { #[derive(Debug)] struct MockDatabricksClient { chunks: Vec>, + calls: std::sync::Mutex>, + page_started: tokio::sync::Notify, + blocked_pages: HashMap>, + fail_first_page: Option, } impl MockDatabricksClient { fn new(chunks: Vec>) -> Self { - Self { chunks } + Self { + chunks, + calls: std::sync::Mutex::new(Vec::new()), + page_started: tokio::sync::Notify::new(), + blocked_pages: HashMap::new(), + fail_first_page: None, + } } } @@ -1224,6 +1242,21 @@ mod tests { _row_offset: i64, _session_attribution: SessionAttribution, ) -> Result { + let first_call = { + let mut calls = self.calls.lock().unwrap(); + let first = !calls.contains(&chunk_index); + calls.push(chunk_index); + first + }; + if first_call { + if let Some(gate) = self.blocked_pages.get(&chunk_index) { + self.page_started.notify_one(); + gate.notified().await; + } + if self.fail_first_page == Some(chunk_index) { + return Err(Error::io().message("injected page fetch failure")); + } + } let index = chunk_index as usize; if index >= self.chunks.len() { return Ok(ChunkLinkFetchResult::end_of_stream()); @@ -1473,6 +1506,64 @@ mod tests { ); } + #[tokio::test] + async fn foreground_miss_shares_current_page_without_waiting_for_lookahead() { + for fail_first in [false, true] { + let mut client = MockDatabricksClient::new(vec![ + vec![create_test_link(0)], + vec![create_test_link(1)], + vec![create_test_link_terminal(2)], + ]); + let first_page = Arc::new(tokio::sync::Notify::new()); + let next_page = Arc::new(tokio::sync::Notify::new()); + client.blocked_pages.insert(1, Arc::clone(&first_page)); + client.blocked_pages.insert(2, Arc::clone(&next_page)); + client.fail_first_page = fail_first.then_some(1); + let client = Arc::new(client); + let fetcher = SeaChunkLinkFetcher::new( + Arc::clone(&client) as Arc, + "test-statement", + &[create_test_link(0)], + Some(3), + 2, + tokio::runtime::Handle::current(), + SessionAttribution::Current, + ); + let handle = SeaChunkLinkFetcherHandle::new(fetcher); + let timeout = std::time::Duration::from_secs(5); + tokio::time::timeout(timeout, client.page_started.notified()) + .await + .unwrap(); + let mut foreground = Box::pin(handle.fetch_links(1, 0)); + assert!(futures::poll!(foreground.as_mut()).is_pending()); + assert_eq!(*client.calls.lock().unwrap(), vec![1]); + + first_page.notify_one(); + let result = tokio::time::timeout(timeout, foreground) + .await + .unwrap() + .unwrap(); + assert_eq!(result.links[0].chunk_index, 1); + if fail_first { + assert_eq!(*client.calls.lock().unwrap(), vec![1, 1]); + } else { + tokio::time::timeout(timeout, client.page_started.notified()) + .await + .unwrap(); + assert_eq!(*client.calls.lock().unwrap(), vec![1, 2]); + assert!(!handle.inner.has_link(2)); + next_page.notify_one(); + tokio::time::timeout(timeout, async { + while handle.inner.prefetch_in_progress.load(Ordering::Acquire) { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + } + } + } + #[tokio::test] async fn test_sea_link_fetcher_with_initial_links() { let links = vec![ From eabe1a54b1c9cac1ba29bbc88cc9eb1a3d77c92d Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sat, 14 Nov 2026 05:56:21 +0000 Subject: [PATCH 3/9] fix(cloudfetch): preserve scheduling notifications when prefetch retires Signed-off-by: Aakash Saravanan --- src/reader/cloudfetch/link_fetcher.rs | 109 +++++++++++++++----------- 1 file changed, 65 insertions(+), 44 deletions(-) diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 008a2dc6..0f1b5ab0 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -686,27 +686,25 @@ impl SeaChunkLinkFetcher { return; } + let consumer_pos = self.current_consumer_index.load(Ordering::SeqCst); + let server_fetch_idx = self.next_server_fetch_index.load(Ordering::Acquire); + let target_index = consumer_pos + self.link_prefetch_window; + + // Check if we need to prefetch + if server_fetch_idx > target_index { + return; + } + // Try to claim prefetch (compare_exchange returns Ok if we won) if self .prefetch_in_progress - .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) .is_err() { // Another prefetch is already in progress return; } - let consumer_pos = self.current_consumer_index.load(Ordering::Acquire); - let server_fetch_idx = self.next_server_fetch_index.load(Ordering::Acquire); - let target_index = consumer_pos + self.link_prefetch_window; - - // Check if we need to prefetch - if server_fetch_idx > target_index { - // We're already ahead of the window, release the flag - self.prefetch_in_progress.store(false, Ordering::Release); - return; - } - debug!( "Triggering async prefetch: consumer={}, server_fetch={}, target={}, window={}", consumer_pos, server_fetch_idx, target_index, self.link_prefetch_window @@ -719,6 +717,12 @@ impl SeaChunkLinkFetcher { }); } + fn release_caught_up_prefetch(self: &Arc) { + // Sequential ordering keeps retiring workers from losing scheduling notifications. + self.prefetch_in_progress.store(false, Ordering::SeqCst); + self.maybe_trigger_prefetch(); + } + /// Background prefetch loop - fetches links until caught up with window. async fn run_prefetch_loop(self: Arc) { loop { @@ -741,7 +745,9 @@ impl SeaChunkLinkFetcher { "Prefetch loop: caught up (server_fetch={} > target={}), stopping", server_fetch_idx, target_index ); - break; + drop(_page); + self.release_caught_up_prefetch(); + return; } // Fetch next batch @@ -841,7 +847,7 @@ impl SeaChunkLinkFetcher { } // Release prefetch flag - self.prefetch_in_progress.store(false, Ordering::Release); + self.prefetch_in_progress.store(false, Ordering::SeqCst); } } @@ -881,7 +887,7 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { fn note_scheduled(&self, chunk_index: i64) { self.inner .current_consumer_index - .fetch_max(chunk_index, Ordering::Release); + .fetch_max(chunk_index, Ordering::SeqCst); self.inner.maybe_trigger_prefetch(); } @@ -1473,37 +1479,52 @@ mod tests { #[tokio::test] async fn scheduled_cached_links_advance_bounded_prefetch() { - let pages: Vec<_> = (0..8).map(|i| vec![create_test_link(i)]).collect(); - let initial: Vec<_> = (0..4).map(create_test_link).collect(); - let fetcher = SeaChunkLinkFetcher::new( - Arc::new(MockDatabricksClient::new(pages)), - "test-statement", - &initial, - Some(8), - 2, - tokio::runtime::Handle::current(), - SessionAttribution::Current, - ); - let handle = SeaChunkLinkFetcherHandle::new(fetcher); - assert!(!handle.inner.has_link(4)); + for coalesced in [false, true] { + let pages: Vec<_> = (0..8).map(|i| vec![create_test_link(i)]).collect(); + let initial: Vec<_> = (0..4).map(create_test_link).collect(); + let client = Arc::new(MockDatabricksClient::new(pages)); + let fetcher = SeaChunkLinkFetcher::new( + Arc::clone(&client) as Arc, + "test-statement", + &initial, + Some(8), + 2, + tokio::runtime::Handle::current(), + SessionAttribution::Current, + ); + let handle = SeaChunkLinkFetcherHandle::new(fetcher); + assert!(!handle.inner.has_link(4)); - handle.note_scheduled(2); - tokio::time::timeout(std::time::Duration::from_secs(5), async { - while handle.inner.prefetch_in_progress.load(Ordering::Acquire) { - tokio::task::yield_now().await; + if coalesced { + handle + .inner + .prefetch_in_progress + .store(true, Ordering::SeqCst); } - }) - .await - .expect("scheduling cached chunk 2 must prefetch the next page"); - - assert!(handle.inner.has_link(3)); - assert!(handle.inner.has_link(4)); - assert!(!handle.inner.has_link(5)); - handle.note_scheduled(1); - assert_eq!( - handle.inner.current_consumer_index.load(Ordering::Acquire), - 2 - ); + handle.note_scheduled(2); + if coalesced { + assert!(client.calls.lock().unwrap().is_empty()); + handle.inner.release_caught_up_prefetch(); + } + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while handle.inner.prefetch_in_progress.load(Ordering::Acquire) { + tokio::task::yield_now().await; + } + }) + .await + .expect("scheduling cached chunk 2 must prefetch the next page"); + + assert!(handle.inner.has_link(3)); + assert!(handle.inner.has_link(4)); + assert!(!handle.inner.has_link(5)); + assert_eq!(*client.calls.lock().unwrap(), vec![4]); + handle.note_scheduled(1); + assert_eq!( + handle.inner.current_consumer_index.load(Ordering::Acquire), + 2 + ); + assert!(!handle.inner.prefetch_in_progress.load(Ordering::Acquire)); + } } #[tokio::test] From 7dd21587e830040787798314f420159a2de93f77 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Sat, 14 Nov 2026 07:35:28 +0000 Subject: [PATCH 4/9] docs(cloudfetch): clarify scheduling prefetch contract Signed-off-by: Aakash Saravanan --- src/reader/cloudfetch/link_fetcher.rs | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 0f1b5ab0..3998cfcc 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -34,11 +34,12 @@ //! and available we approach this boundary //! ``` //! -//! When a link is requested: -//! 1. Return immediately from cache if available -//! 2. Update consumer position tracking -//! 3. Check if prefetch should be triggered (async, non-blocking) -//! 4. Background task fetches links and caches them +//! Link requests and download scheduling advance the consumer position to the +//! highest chunk index seen and check whether to start non-blocking background +//! prefetch, which fetches links and caches them ahead of downloads. +//! +//! Link requests return cached links immediately; on a miss they wait for any +//! page already being prefetched before requesting it. use crate::client::{ChunkLinkFetchResult, SessionAttribution, Transport}; use crate::kernel_error::{Error, Result}; @@ -66,7 +67,10 @@ use tokio::sync::Mutex as TokioMutex; /// Both parameters are passed to methods; implementations use the relevant one. #[async_trait] pub(crate) trait ChunkLinkFetcher: Send + Sync + std::fmt::Debug { - // Cached links can outlive a fetch call, so scheduling must advance the prefetch horizon. + /// Cached links can outlive a fetch call, so scheduling must advance the prefetch horizon. + /// Prefetchers keep the highest `chunk_index` seen because calls may repeat or + /// arrive out of order. This synchronous hook runs inside the download scheduler + /// and must not block. Fetchers without prefetching may use the no-op default. fn note_scheduled(&self, _chunk_index: i64) {} /// Fetch the next batch of chunk links. @@ -147,7 +151,7 @@ pub(crate) trait ChunkLinkFetcher: Send + Sync + std::fmt::Debug { /// /// ## Prefetch Behavior /// -/// When `fetch_links()` is called: +/// When a download is scheduled or `fetch_links()` is called: /// 1. Consumer position is updated /// 2. If `next_server_fetch_index <= consumer_position + link_prefetch_window`, /// a background prefetch task is spawned @@ -215,7 +219,7 @@ pub(crate) struct SeaChunkLinkFetcher { /// avoid spinning, but the empty-with-has_more shape is a /// server bug worth surfacing in production logs. empty_with_has_more_warned: AtomicBool, - /// Current consumer position (highest chunk index requested) + /// Current consumer position (highest chunk index scheduled or requested) current_consumer_index: AtomicI64, /// Number of chunks to prefetch ahead of consumer position link_prefetch_window: i64, From 31d8022096b96af3a8eb8214b51cc5ca19669b12 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 16 Nov 2026 22:27:27 +0000 Subject: [PATCH 5/9] fix(cloudfetch): share page fetch failures with waiting readers Signed-off-by: Aakash Saravanan --- src/reader/cloudfetch/link_fetcher.rs | 288 ++++++++------------ src/reader/cloudfetch/streaming_provider.rs | 73 ++++- 2 files changed, 190 insertions(+), 171 deletions(-) diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 3998cfcc..e6eeb9c9 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -48,8 +48,8 @@ use crate::types::cloudfetch::CloudFetchLink; use async_trait::async_trait; use dashmap::DashMap; use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; -use std::sync::Arc; -use tokio::sync::Mutex as TokioMutex; +use std::sync::{Arc, Mutex}; +use tokio::sync::watch; /// Statement-scoped abstraction for fetching chunk links. /// @@ -227,8 +227,8 @@ pub(crate) struct SeaChunkLinkFetcher { prefetch_in_progress: AtomicBool, /// Tokio runtime handle for spawning prefetch tasks runtime_handle: tokio::runtime::Handle, - /// Foreground misses must share pages already being prefetched. - prefetch_lock: TokioMutex<()>, + /// Joiners share each attempt's error instead of starting another retry budget. + page_fetch: Mutex>>>>, /// Next row offset for pagination (used by some backends) next_row_offset: AtomicI64, } @@ -456,7 +456,7 @@ impl SeaChunkLinkFetcher { link_prefetch_window, prefetch_in_progress: AtomicBool::new(false), runtime_handle, - prefetch_lock: TokioMutex::new(()), + page_fetch: Mutex::new(None), next_row_offset: AtomicI64::new(next_row_offset), }; if fallback_used { @@ -730,9 +730,6 @@ impl SeaChunkLinkFetcher { /// Background prefetch loop - fetches links until caught up with window. async fn run_prefetch_loop(self: Arc) { loop { - // Release between pages so a waiting reader can use the page just fetched. - let _page = self.prefetch_lock.lock().await; - // Check if we're done if self.all_links_fetched.load(Ordering::Acquire) { debug!("Prefetch loop: all links fetched, stopping"); @@ -749,7 +746,6 @@ impl SeaChunkLinkFetcher { "Prefetch loop: caught up (server_fetch={} > target={}), stopping", server_fetch_idx, target_index ); - drop(_page); self.release_caught_up_prefetch(); return; } @@ -761,90 +757,11 @@ impl SeaChunkLinkFetcher { server_fetch_idx, row_offset ); - match self - .client - .get_result_chunks( - &self.statement_id, - server_fetch_idx, - row_offset, - self.session_attribution, - ) - .await - { - Ok(result) => { - // Cache the new links. - for link in &result.links { - self.links.insert(link.chunk_index, link.clone()); - } - - // The continuation signal comes from - // `decode_continuation`: prefer the per-link - // `next_chunk_index` (bounded SEA API - // contract); fall back to `total_chunk_count` - // only when the server hasn't rolled out the - // new field. Forward progress is guarded — - // `fetch_max` and a separate - // `max(chunk_index+1)` floor prevent a - // non-monotonic server response from driving - // `next_server_fetch_index` backwards. - // - // Setting `all_links_fetched = true` here just - // stops the prefetch loop; in-flight chunk - // downloads continue independently. - if let Some(last_link) = result.links.last() { - let last_chunk_index = last_link.chunk_index; - let links_count = result.links.len(); - let advance_to = self.apply_continuation(last_link, "prefetch loop"); - if self.all_links_fetched.load(Ordering::Acquire) { - debug!("Prefetch loop: end-of-stream on link {}", last_chunk_index,); - break; - } - debug!( - "Prefetch loop: fetched {} links (last chunk {}), \ - next_server_fetch={}", - links_count, last_chunk_index, advance_to, - ); - } else if !result.has_more { - // Defensive: server returned no links and - // signalled no more. Treat as end-of-stream - // for link discovery. - debug!("Prefetch loop: empty response with has_more=false"); - self.all_links_fetched.store(true, Ordering::Release); - break; - } else { - // Empty batch but `has_more` is true. Force - // forward progress so the loop can't spin - // re-issuing the same RPC. Two strategies: - // 1. If the server gave us a - // `next_chunk_index` hint, use it. - // 2. Otherwise bump past - // `server_fetch_idx` ourselves. - // Either way, on the next iteration we'll - // ask for a *different* chunk index, which - // breaks the loop. If the server keeps - // returning empty-with-has_more, that's a - // server bug we surface via the - // `current_consumer_index` heuristic in - // streaming_provider (consumer never - // advances → chunks_in_memory stays full - // → prefetch pauses) AND via the - // `empty_with_has_more_warned` one-shot. - let advance_to = result - .next_chunk_index - .unwrap_or_else(|| server_fetch_idx.saturating_add(1)); - self.next_server_fetch_index - .fetch_max(advance_to, Ordering::Release); - self.warn_empty_with_has_more( - "prefetch loop", - server_fetch_idx, - advance_to, - ); - break; - } - } + match self.fetch_page(server_fetch_idx, row_offset).await { + Ok(true) => {} + Ok(false) => break, Err(e) => { error!("Prefetch loop: failed to fetch links: {}", e); - // Don't propagate error - let the main fetch_links handle it break; } } @@ -853,6 +770,71 @@ impl SeaChunkLinkFetcher { // Release prefetch flag self.prefetch_in_progress.store(false, Ordering::SeqCst); } + + async fn fetch_page(self: &Arc, chunk_index: i64, row_offset: i64) -> Result { + let mut completion = { + let mut in_flight = self.page_fetch.lock().unwrap(); + if self.all_links_fetched.load(Ordering::Acquire) + || chunk_index < self.next_server_fetch_index.load(Ordering::Acquire) + { + return Ok(true); + } + if let Some(completion) = in_flight.as_ref() { + completion.clone() + } else { + let (sender, completion) = watch::channel(None); + *in_flight = Some(completion.clone()); + let fetcher = Arc::clone(self); + // A cancelled waiter must not abandon the attempt or strand other joiners. + self.runtime_handle.spawn(async move { + let result = fetcher + .fetch_page_from_server(chunk_index, row_offset) + .await; + let mut in_flight = fetcher.page_fetch.lock().unwrap(); + sender.send_replace(Some(result)); + *in_flight = None; + }); + completion + } + }; + loop { + if let Some(result) = completion.borrow().clone() { + return result; + } + completion.changed().await.map_err(|_| { + Error::invalid_state().message("Link page fetch ended without a result") + })?; + } + } + + async fn fetch_page_from_server(&self, chunk_index: i64, row_offset: i64) -> Result { + let result = self + .client + .get_result_chunks( + &self.statement_id, + chunk_index, + row_offset, + self.session_attribution, + ) + .await?; + for link in &result.links { + self.links.insert(link.chunk_index, link.clone()); + } + if let Some(last_link) = result.links.last() { + self.apply_continuation(last_link, "page fetch"); + } else if !result.has_more { + self.all_links_fetched.store(true, Ordering::Release); + } else { + // Empty pages must advance so later attempts cannot spin on the same request. + let advance_to = result + .next_chunk_index + .unwrap_or_else(|| chunk_index.saturating_add(1)); + self.next_server_fetch_index + .fetch_max(advance_to, Ordering::Release); + self.warn_empty_with_has_more("page fetch", chunk_index, advance_to); + } + Ok(!result.links.is_empty()) + } } /// Wrapper to allow calling `maybe_trigger_prefetch` from the trait implementation. @@ -904,13 +886,16 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { self.note_scheduled(start_chunk_index); - let _fallback = if !fetcher.all_links_fetched.load(Ordering::Acquire) + while !fetcher.all_links_fetched.load(Ordering::Acquire) && start_chunk_index >= fetcher.next_server_fetch_index.load(Ordering::Acquire) { - Some(fetcher.prefetch_lock.lock().await) - } else { - None - }; + if !fetcher + .fetch_page(start_chunk_index, start_row_offset) + .await? + { + break; + } + } // If we already have all links, return what we have from cache. // Walk contiguously from `start_chunk_index` until we hit a @@ -963,73 +948,10 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { }); } - // Fetch from server (synchronous fallback if prefetch hasn't caught up) - debug!( - "SeaChunkLinkFetcher: cache miss for chunk {}, fetching synchronously", - start_chunk_index - ); - let result = fetcher - .client - .get_result_chunks( - &fetcher.statement_id, - start_chunk_index, - start_row_offset, - fetcher.session_attribution, - ) - .await?; - - // Cache the new links. - for link in &result.links { - fetcher.links.insert(link.chunk_index, link.clone()); - } - - // Advance via the shared `apply_continuation` helper so - // prefetch-loop and sync-fallback share the same bridge - // logic for the total_chunk_count rollout, the same - // forward-progress clamp, and the same one-shot warnings. - let next_chunk_index = match result.links.last() { - Some(last_link) => { - let advance_to = fetcher.apply_continuation(last_link, "sync fallback"); - if fetcher.all_links_fetched.load(Ordering::Acquire) { - None - } else { - Some(advance_to) - } - } - None => { - // Empty response. Honour the server's has_more - // signal AND defend against an empty-with-has_more - // spin: force forward progress on - // next_server_fetch_index so the next call asks - // for a different chunk index. The server is - // expected to either yield links or signal - // end-of-stream — a perpetual "I have more but - // here are zero links" loop is a server bug we - // refuse to amplify into an infinite local retry. - if !result.has_more { - fetcher.all_links_fetched.store(true, Ordering::Release); - } else { - let advance_to = result - .next_chunk_index - .unwrap_or_else(|| start_chunk_index.saturating_add(1)); - fetcher - .next_server_fetch_index - .fetch_max(advance_to, Ordering::Release); - fetcher.warn_empty_with_has_more( - "sync fallback", - start_chunk_index, - advance_to, - ); - } - None - } - }; - - let has_more = !fetcher.all_links_fetched.load(Ordering::Acquire); Ok(ChunkLinkFetchResult { - links: result.links, - has_more, - next_chunk_index: if has_more { next_chunk_index } else { None }, + links: Vec::new(), + has_more: !fetcher.all_links_fetched.load(Ordering::Acquire), + next_chunk_index: Some(fetcher.next_server_fetch_index.load(Ordering::Acquire)), next_row_offset: Some(fetcher.next_row_offset.load(Ordering::Acquire)), }) } @@ -1264,7 +1186,9 @@ mod tests { gate.notified().await; } if self.fail_first_page == Some(chunk_index) { - return Err(Error::io().message("injected page fetch failure")); + return Err(Error::io() + .message("injected page fetch failure") + .with_sql_state("08001")); } } let index = chunk_index as usize; @@ -1563,15 +1487,41 @@ mod tests { assert!(futures::poll!(foreground.as_mut()).is_pending()); assert_eq!(*client.calls.lock().unwrap(), vec![1]); + let mut other_reader = Box::pin(handle.fetch_links(1, 0)); + assert!(futures::poll!(other_reader.as_mut()).is_pending()); + let mut dropped_reader = Box::pin(handle.fetch_links(1, 0)); + assert!(futures::poll!(dropped_reader.as_mut()).is_pending()); + drop(dropped_reader); first_page.notify_one(); - let result = tokio::time::timeout(timeout, foreground) - .await - .unwrap() - .unwrap(); - assert_eq!(result.links[0].chunk_index, 1); + let result = tokio::time::timeout(timeout, foreground).await.unwrap(); + let other_result = tokio::time::timeout(timeout, other_reader).await.unwrap(); if fail_first { - assert_eq!(*client.calls.lock().unwrap(), vec![1, 1]); + for result in [result, other_result] { + let error = result.unwrap_err(); + assert_eq!(error.message, "injected page fetch failure"); + assert_eq!(error.sql_state.as_deref(), Some("08001")); + } + assert_eq!(*client.calls.lock().unwrap(), vec![1]); + // A later request can retry after the joined attempt has failed. + let retry = tokio::time::timeout(timeout, handle.fetch_links(1, 0)) + .await + .unwrap() + .unwrap(); + assert_eq!(retry.links[0].chunk_index, 1); + assert_eq!( + client + .calls + .lock() + .unwrap() + .iter() + .filter(|&&i| i == 1) + .count(), + 2 + ); + next_page.notify_one(); } else { + assert_eq!(result.unwrap().links[0].chunk_index, 1); + assert_eq!(other_result.unwrap().links[0].chunk_index, 1); tokio::time::timeout(timeout, client.page_started.notified()) .await .unwrap(); diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index 9c536ea7..b2683ca1 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -445,7 +445,12 @@ impl StreamingCloudFetchProvider { // Fetch initial batch of links (should be instant if cached by link fetcher) debug!("Initializing provider: fetching initial links"); - match self.link_fetcher.fetch_links(0, 0).await { + let result = tokio::select! { + biased; + _ = self.cancel_token.cancelled() => return, + result = self.link_fetcher.fetch_links(0, 0) => result, + }; + match result { Ok(result) => { // Store fetched links for link in result.links { @@ -514,6 +519,9 @@ impl StreamingCloudFetchProvider { if self.release_downloaded_chunk(chunk_index) { // Schedule more downloads self.schedule_downloads().await; + if self.cancel_token.is_cancelled() { + return Err(Error::invalid_state().message("Operation cancelled")); + } // Return first batch from buffer if let Some(batch) = self.take_buffered_batch() { @@ -688,7 +696,12 @@ impl StreamingCloudFetchProvider { /// /// Returns whether the requested `start_index` is now available in the map. async fn fetch_and_store_links(&self, start_index: i64) -> bool { - match self.link_fetcher.fetch_links(start_index, 0).await { + let result = tokio::select! { + biased; + _ = self.cancel_token.cancelled() => return false, + result = self.link_fetcher.fetch_links(start_index, 0) => result, + }; + match result { Ok(result) => { for link in result.links { let chunk_index = link.chunk_index; @@ -1730,6 +1743,7 @@ mod tests { links_by_index: HashMap, total_chunks: i64, scheduled: Mutex>, + fetch_gate: Option>, } impl MockLinkFetcher { @@ -1743,6 +1757,7 @@ mod tests { links_by_index, total_chunks, scheduled: Mutex::new(Vec::new()), + fetch_gate: None, } } } @@ -1758,6 +1773,9 @@ mod tests { start_chunk_index: i64, _start_row_offset: i64, ) -> Result { + if let Some(gate) = &self.fetch_gate { + gate.notified().await; + } if start_chunk_index >= self.total_chunks { return Ok(ChunkLinkFetchResult::end_of_stream()); } @@ -1825,6 +1843,57 @@ mod tests { } } + #[tokio::test] + async fn cancellation_interrupts_link_fetch_during_refill_and_initialization() { + for initial in [false, true] { + let mut fetcher = MockLinkFetcher::new(2); + fetcher.fetch_gate = Some(Arc::new(Notify::new())); + let chunks = Arc::new(DashMap::new()); + let batch = RecordBatch::new_empty(Arc::new(Schema::empty())); + chunks.insert( + 0, + ChunkEntry { + link: Some(create_test_link(0)), + state: ChunkState::Downloaded, + batches: Some(vec![batch]), + ..ChunkEntry::with_link(create_test_link(0)) + }, + ); + let provider = StreamingCloudFetchProvider::for_test_with_chunks( + Arc::new(fetcher), + noop_downloader(), + chunks, + false, + ); + provider.chunks_in_memory.store(1, Ordering::Release); + provider.next_download_index.store(1, Ordering::Release); + if initial { + let mut initialize = Box::pin(provider.initialize()); + assert!(futures::poll!(initialize.as_mut()).is_pending()); + provider.cancel(); + tokio::time::timeout(NO_HANG, initialize).await.unwrap(); + } else { + let mut read = Box::pin(provider.next_batch()); + assert!(futures::poll!(read.as_mut()).is_pending()); + assert_eq!(provider.current_chunk_index.load(Ordering::Acquire), 1); + provider.cancel(); + assert!(tokio::time::timeout(NO_HANG, read) + .await + .unwrap() + .unwrap_err() + .message + .contains("cancel")); + } + assert!(provider.terminal_error().is_none()); + assert!(provider + .next_batch() + .await + .unwrap_err() + .message + .contains("cancel")); + } + } + #[tokio::test] async fn bounded_downloads_notify_each_scheduled_chunk_in_order() { use crate::client::retry::{build_retry_configs, RetryConfig}; From 39d4fac74a4a4432622f2eff715c1518e8a51127 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 16 Nov 2026 22:30:36 +0000 Subject: [PATCH 6/9] docs(cloudfetch): describe shared page attempt results Signed-off-by: Aakash Saravanan --- src/reader/cloudfetch/link_fetcher.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index e6eeb9c9..82f7a15d 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -38,8 +38,8 @@ //! highest chunk index seen and check whether to start non-blocking background //! prefetch, which fetches links and caches them ahead of downloads. //! -//! Link requests return cached links immediately; on a miss they wait for any -//! page already being prefetched before requesting it. +//! Link requests return cached links immediately. Cache misses join any in-flight +//! page request and share its result, including errors. use crate::client::{ChunkLinkFetchResult, SessionAttribution, Transport}; use crate::kernel_error::{Error, Result}; From e5f4d1a8f82fc41f40dc8b637fe2362280d15441 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 16 Nov 2026 22:54:41 +0000 Subject: [PATCH 7/9] docs(cloudfetch): clarify bounded empty-page retries Signed-off-by: Aakash Saravanan --- src/reader/cloudfetch/link_fetcher.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 82f7a15d..40376038 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -825,7 +825,7 @@ impl SeaChunkLinkFetcher { } else if !result.has_more { self.all_links_fetched.store(true, Ordering::Release); } else { - // Empty pages must advance so later attempts cannot spin on the same request. + // Retrying here could loop forever on a non-advancing continuation. let advance_to = result .next_chunk_index .unwrap_or_else(|| chunk_index.saturating_add(1)); @@ -1502,7 +1502,6 @@ mod tests { assert_eq!(error.sql_state.as_deref(), Some("08001")); } assert_eq!(*client.calls.lock().unwrap(), vec![1]); - // A later request can retry after the joined attempt has failed. let retry = tokio::time::timeout(timeout, handle.fetch_links(1, 0)) .await .unwrap() From 1a8e2e548c04e1d34aa8b0ea45bc8eb735f3a31b Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Mon, 16 Nov 2026 23:23:20 +0000 Subject: [PATCH 8/9] fix(cloudfetch): match shared completion to requested page Signed-off-by: Aakash Saravanan --- src/reader/cloudfetch/link_fetcher.rs | 81 +++++++++++++++++++++++---- 1 file changed, 71 insertions(+), 10 deletions(-) diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 40376038..a659c154 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -38,8 +38,9 @@ //! highest chunk index seen and check whether to start non-blocking background //! prefetch, which fetches links and caches them ahead of downloads. //! -//! Link requests return cached links immediately. Cache misses join any in-flight -//! page request and share its result, including errors. +//! Link requests return cached links immediately. Cache misses wait for in-flight +//! page requests and recheck the cache. Readers waiting on the same page share its +//! result, including errors. use crate::client::{ChunkLinkFetchResult, SessionAttribution, Transport}; use crate::kernel_error::{Error, Result}; @@ -134,6 +135,11 @@ pub(crate) trait ChunkLinkFetcher: Send + Sync + std::fmt::Debug { } } +struct PageFetch { + chunk_index: i64, + completion: watch::Receiver>>, +} + /// SEA implementation of ChunkLinkFetcher with caching and proactive prefetching. /// /// This fetcher: @@ -227,8 +233,8 @@ pub(crate) struct SeaChunkLinkFetcher { prefetch_in_progress: AtomicBool, /// Tokio runtime handle for spawning prefetch tasks runtime_handle: tokio::runtime::Handle, - /// Joiners share each attempt's error instead of starting another retry budget. - page_fetch: Mutex>>>>, + /// Same-page joiners share errors instead of starting another retry budget. + page_fetch: Mutex>, /// Next row offset for pagination (used by some backends) next_row_offset: AtomicI64, } @@ -772,18 +778,21 @@ impl SeaChunkLinkFetcher { } async fn fetch_page(self: &Arc, chunk_index: i64, row_offset: i64) -> Result { - let mut completion = { + let (page_index, mut completion) = { let mut in_flight = self.page_fetch.lock().unwrap(); if self.all_links_fetched.load(Ordering::Acquire) || chunk_index < self.next_server_fetch_index.load(Ordering::Acquire) { return Ok(true); } - if let Some(completion) = in_flight.as_ref() { - completion.clone() + if let Some(attempt) = in_flight.as_ref() { + (attempt.chunk_index, attempt.completion.clone()) } else { let (sender, completion) = watch::channel(None); - *in_flight = Some(completion.clone()); + *in_flight = Some(PageFetch { + chunk_index, + completion: completion.clone(), + }); let fetcher = Arc::clone(self); // A cancelled waiter must not abandon the attempt or strand other joiners. self.runtime_handle.spawn(async move { @@ -794,12 +803,17 @@ impl SeaChunkLinkFetcher { sender.send_replace(Some(result)); *in_flight = None; }); - completion + (chunk_index, completion) } }; loop { if let Some(result) = completion.borrow().clone() { - return result; + // A refresh can advance the cursor past this attempt while it is pending. + return if page_index == chunk_index { + result + } else { + Ok(true) + }; } completion.changed().await.map_err(|_| { Error::invalid_state().message("Link page fetch ended without a result") @@ -1538,6 +1552,53 @@ mod tests { } } + #[tokio::test] + async fn foreground_miss_fetches_own_page_after_joining_another_attempt() { + for fail_earlier in [false, true] { + let mut client = MockDatabricksClient::new(vec![ + vec![create_test_link(0), create_test_link(1)], + vec![], + vec![create_test_link_terminal(2)], + ]); + let earlier_page = Arc::new(tokio::sync::Notify::new()); + client.blocked_pages.insert(1, Arc::clone(&earlier_page)); + client.fail_first_page = fail_earlier.then_some(1); + let client = Arc::new(client); + let handle = SeaChunkLinkFetcherHandle::new(SeaChunkLinkFetcher::new( + Arc::clone(&client) as Arc, + "test-statement", + &[create_test_link(0)], + Some(3), + 2, + tokio::runtime::Handle::current(), + SessionAttribution::Current, + )); + let timeout = std::time::Duration::from_secs(5); + tokio::time::timeout(timeout, client.page_started.notified()) + .await + .unwrap(); + let refreshed = handle.refetch_links_from(0, 0).await.unwrap(); + assert_eq!(refreshed.last().unwrap().chunk_index, 1); + let mut foreground = Box::pin(handle.fetch_links(2, 0)); + assert!(futures::poll!(foreground.as_mut()).is_pending()); + earlier_page.notify_one(); + let result = tokio::time::timeout(timeout, foreground) + .await + .unwrap() + .unwrap(); + assert_eq!( + result + .links + .iter() + .map(|link| link.chunk_index) + .collect::>(), + vec![2] + ); + assert!(!result.has_more); + assert_eq!(*client.calls.lock().unwrap(), vec![1, 0, 2]); + } + } + #[tokio::test] async fn test_sea_link_fetcher_with_initial_links() { let links = vec![ From 16bc3c4b3c9413b8a1ac7827d220fde1718d4467 Mon Sep 17 00:00:00 2001 From: Aakash Saravanan Date: Tue, 17 Nov 2026 00:04:56 +0000 Subject: [PATCH 9/9] fix(cloudfetch): bound page retries and retain cached result tail Signed-off-by: Aakash Saravanan --- src/reader/cloudfetch/link_fetcher.rs | 47 ++++++++++++++++++++++++--- 1 file changed, 43 insertions(+), 4 deletions(-) diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index a659c154..9455f0a2 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -836,6 +836,13 @@ impl SeaChunkLinkFetcher { } if let Some(last_link) = result.links.last() { self.apply_continuation(last_link, "page fetch"); + if !self.all_links_fetched.load(Ordering::Acquire) + && self.next_server_fetch_index.load(Ordering::Acquire) <= chunk_index + { + return Err(Error::invalid_state().message(format!( + "Link page did not advance past chunk {chunk_index}" + ))); + } } else if !result.has_more { self.all_links_fetched.store(true, Ordering::Release); } else { @@ -953,18 +960,18 @@ impl ChunkLinkFetcher for SeaChunkLinkFetcherHandle { // `i` is now either `server_fetch_index` (no holes) or // the first missing chunk_index — in either case it's // where the next continuation should pick up. - let has_more = !fetcher.all_links_fetched.load(Ordering::Acquire); + // A final page can arrive after this prefix was bounded. return Ok(ChunkLinkFetchResult { links, - has_more, - next_chunk_index: if has_more { Some(i) } else { None }, + has_more: true, + next_chunk_index: Some(i), next_row_offset: None, }); } Ok(ChunkLinkFetchResult { links: Vec::new(), - has_more: !fetcher.all_links_fetched.load(Ordering::Acquire), + has_more: true, next_chunk_index: Some(fetcher.next_server_fetch_index.load(Ordering::Acquire)), next_row_offset: Some(fetcher.next_row_offset.load(Ordering::Acquire)), }) @@ -1599,6 +1606,38 @@ mod tests { } } + #[tokio::test] + async fn nonadvancing_nonempty_page_returns_shared_error() { + let mut client = + MockDatabricksClient::new(vec![vec![create_test_link(0)], vec![create_test_link(0)]]); + let page = Arc::new(tokio::sync::Notify::new()); + client.blocked_pages.insert(1, Arc::clone(&page)); + let client = Arc::new(client); + let handle = SeaChunkLinkFetcherHandle::new(SeaChunkLinkFetcher::new( + Arc::clone(&client) as Arc, + "test-statement", + &[create_test_link(0)], + Some(2), + 2, + tokio::runtime::Handle::current(), + SessionAttribution::Current, + )); + let timeout = std::time::Duration::from_secs(5); + tokio::time::timeout(timeout, client.page_started.notified()) + .await + .unwrap(); + let mut foreground = Box::pin(handle.fetch_links(1, 0)); + assert!(futures::poll!(foreground.as_mut()).is_pending()); + page.notify_one(); + let error = tokio::time::timeout(timeout, foreground) + .await + .unwrap() + .unwrap_err(); + assert_eq!(error.code, crate::kernel_error::ErrorCode::InvalidArgument); + assert_eq!(error.message, "Link page did not advance past chunk 1"); + assert_eq!(*client.calls.lock().unwrap(), vec![1]); + } + #[tokio::test] async fn test_sea_link_fetcher_with_initial_links() { let links = vec![